问题描述
||
为什么我不能使用函数设置公共成员变量?
<?
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__ ;
否则,您将必须在ѭ5或中初始化$this->currentDir
。
, 根据PHP手册,您的实例变量:
必须能够在
编译时间,不能依赖
运行时信息以便
被评估
因此,您不能在属性初始化中使用dirname函数。因此,只需使用构造函数即可通过以下方式设置默认值:
public function __construct() {
$this->currentDir = dirname( __FILE__ );
}
, 指定属性时,不能调用函数。
使用此代替:
<?php
class TestClass{
public $currentDir = null;
public function TestClass()
{
$this->currentDir = dirname(__FILE__);
/* the rest here */
}
}
, 为成员变量指定默认值时,您似乎无法调用函数。
, 遗憾的是,您无法调用函数来声明类变量。但是,您可以从构造函数中将dirname(FILE)的返回值分配给$ this-> currentDir。
编辑:请注意:PHP => 5中的构造函数称为__construct(),而不是类的名称。
, 您可以改用以下方法:
public $currentDir = \'\';
public function TestClass()
{
$this->currentDir = dirname( __FILE__ );
...
, dirname
表达式引起错误,您无法在此处将表达式声明为变量。您可以这样做。
<?
class TestClass {
public $thisWorks = \"something\";
public $currentDir;
public function __construct()
{
$this->currentDir = dirname( __FILE__ );
}
public function test()
{
echo $this->currentDir;
}
}
每次实例化新类时,都将在构造函数中设置目录名。我还建议在文件中省略结尾的php标签?>。有助于缓解和发送标头错误
, 原因是您不能以静态方式使用函数分配实例变量。 PHP根本不允许这样做。
我可以建议您这样做:
<?
class Foo {
public $currentDir;
public function __construct() {
$this->currentDir = dirname(__FILE__);
}
}
?>
, 在构造函数中完成。
$ this-> currentDir = dirname(FILE);
顺便说一下
打印$ currentDir。 \“ \\ n \”;
在类中调用vars时使用$ this