尝试使用方法外部的dirname()初始化此公共类变量时出错

Why can't I set a public member variable using a function?

<?

class TestClass {

    public $thisWorks = "something";

    public $currentDir = dirname( __FILE__ );

    public function TestClass()
    {
        print $this->thisWorks . "
";
        print $this->currentDir . "
";
    }

}

$myClass = new TestClass();

?>

Running it yields:

Parse error: syntax error, unexpected '(', expecting ',' or ';' in /tmp/tmp.php on line 7

You cannot have expressions in the variable declarations. You can only use constant values. The dirname() may not appear in this position.

If you were to use PHP 5.3 you could use:

  public $currentDir = __DIR__ ;

Otherwise you will have to initialize $this->currentDir in the __constructor.

Looks like you can not call functions when specifying default values for member variables.

The reason is that you cannot assign instance variables using functions in a static manner. It is simply not allowed in PHP.

May I suggest you do this:

<?
class Foo {
    public $currentDir;

    public function __construct() {
        $this->currentDir = dirname(__FILE__);
    }
}
?>

You can't call functions to declare class variables, sadly. You could, however, assign the return value from dirname( FILE ) to $this->currentDir from within the constructor.

EDIT: Mind you: the constructor in PHP => 5 is called __construct( ), not the name of the class.

You cannot call functions when you specify attributes.

Use this instead:

<?php

class TestClass{

    public $currentDir = null;

    public function TestClass()
    {
        $this->currentDir = dirname(__FILE__);
        /* the rest here */
    }
}

do it in the constructor. $this->currentDir = dirname( FILE );

and by the way print $currentDir . " "; use $this when calling vars in class

You can use this instead:

public $currentDir = '';

public function TestClass()
{
    $this->currentDir = dirname( __FILE__ );
    ...

As per the PHP manual, your instance variables:

must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated

As such, you can't use the dirname function in the property initialisation. Therefore, simply use a constructor to set the default value via:

public function __construct() {
    $this->currentDir = dirname( __FILE__ );
}

The dirname expression is causing the error you can not declare an expression as a variable there. You could do this though.

<?

class TestClass {

    public $thisWorks = "something";
    public $currentDir;

    public function __construct()
    {
        $this->currentDir = dirname( __FILE__ );
    }

    public function test()
    {
        echo $this->currentDir;
    }
}

Everytime you instantiate a new class the dirname will be set in the constructor. I also recommend omitting the closing php tag ?> in your files. Helps to alleviate and header sent errors