Php 为什么可以';我是否使用占位符从类调用静态属性?
为什么我不能使用占位符从类调用静态属性 举例说明:Php 为什么可以';我是否使用占位符从类调用静态属性?,php,class,Php,Class,为什么我不能使用占位符从类调用静态属性 举例说明: class Foo { public $obj_property = 'works'; public static $static_property = 'does not work'; } /**this works*/ $foo = new Foo(); $obj_prop = 'obj_property'; echo $foo->$obj_prop; /**this fails*/ $static_prop
class Foo {
public $obj_property = 'works';
public static $static_property = 'does not work';
}
/**this works*/
$foo = new Foo();
$obj_prop = 'obj_property';
echo $foo->$obj_prop;
/**this fails*/
$static_prop = '$static_property';
echo Foo::$static_prop;
返回的错误是访问未声明的静态属性:Foo::$static\u prop
。
我知道它试图寻找不存在的$static\u prop
。但它为什么这样做呢?它是否应该查找
$static\u property
-bc,即$static\u prop
的值
我很抱歉,如果这个问题已经被问过了-找遍了,但找不到它
(Edit:它询问如何访问变量。我的问题更多的是问为什么而不是如何。但另一个问题肯定是相关的和有用的。)表达式
Foo::$static\u prop
的意思是“类Foo
中定义的静态变量static\u prop
这句话的意思是:
$static_prop = 'static_property';
echo Foo::$$static_prop;
使用双美元表达式时,首先将
$static\u prop
计算为'static\u property'
,然后可以找到Foo::$static\u property
。这是否回答了您的问题?'$static\u property'
中的$/code>只是一个字面上的美元符号。从PHP的角度来看,它没有任何特殊意义。