currentDir . "\n"; } } $myCla-6ren">
gpt4 book ai didi

php - 尝试在方法外使用 dirname() 初始化此公共(public)类变量时出错

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:52:08 25 4
gpt4 key购买 nike

为什么我不能使用函数设置公共(public)成员变量?

<?

class TestClass {

public $thisWorks = "something";

public $currentDir = dirname( __FILE__ );

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

}

$myClass = new TestClass();

?>

运行它会产生:

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

最佳答案

变量声明中不能有表达式。您只能使用常量值。 dirname() 可能不会出现在这个位置。

如果您要使用 PHP 5.3,您可以使用:

  public $currentDir = __DIR__ ;

否则,您将不得不在 __construct 或中初始化 $this->currentDir

关于php - 尝试在方法外使用 dirname() 初始化此公共(public)类变量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6155965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com