我在另一个类中调用类的静态属性时遇到问题。
Class A {
public $property;
public function __construct( $prop ) {
$this->property = $prop;
}
public function returnValue(){
return static::$this->property;
}
}
Class B extends A {
public static $property_one = 'This is first property';
public static $property_two = 'This is second property';
}
$B = new B( 'property_one' );
$B->returnValue();
我希望返回This is first property
但输出只是__construct中参数输入的名称;
当我print_r( static::$this->property );
时,输出只是property_one
答案 0 :(得分:1)
也许是这样的?
<?php
Class A {
public $property;
public function __construct( $prop ) {
$this->property = $prop;
print static::${$this->property};
}
}
Class B extends A {
public static $property_one = 'This is first property';
public static $property_two = 'This is second property';
}
$B = new B( 'property_one' );
(我的意思是你可以通过这种方式访问(打印,...)属性,但构造函数无论如何都会返回一个对象。)
答案 1 :(得分:1)
只需改变:
return static::$this->property;
使用:
return static::${$this->property};
答案 2 :(得分:1)
这里有几个问题:
$property_one
在类B
中声明,A
类的构造函数不能访问该属性,也不能保证此属性存在。$this->property
或static::$propery
。请注意self::$property
!当您撰写$
时,您希望将其评估为static::$this->property
。您显然错过了self::property_one
标志
至少你需要的是$
。查看变量变量的PHP手册。要在构造函数中访问子类的静态属性,您不能不依赖于子构造函数:
self::${$this->property}
另一种选择是:
Class A
{
public $property;
}
Class B extends A
{
public static $property_one = 'This is first property';
public static $property_two = 'This is second property';
public function __construct( $prop )
{
$this->property = $prop;
print self::${$this->property};
}
}
$B = new B( 'property_one' );