[英]Call static properties within another class in php
我在调用另一个类中的某个类的静态属性时遇到问题。
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
但是Output只是在__construct中输入的参数名称;
当我print_r( static::$this->property );
输出只是property_one
也许是这样吗?
<?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' );
(我的意思是,您可以通过这种方式访问(打印,...)该属性,但是构造函数仍然会返回一个对象。)
只是改变:
return static::$this->property;
与:
return static::${$this->property};
这里有几个问题:
$property_one
在类B
声明, A
类的构造函数将无法访问该属性,也不能保证该属性存在。 $this->property
分配。 如果分配了对象怎么办? 一个int还是float? static::$propery
或self::$property
。 注意$
! 当您编写static::$this->property
,您希望它的计算结果为self::property_one
。 您显然缺少$
符号。 self::${$this->property}
。 查看有关变量变量的PHP手册。 要访问构造函数中子类的静态属性,您只能依靠子构造函数:
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' );
一种替代方法是:
Class A
{
public $property;
public function __constructor($prop)
{
$this->property = $prop;
}
public function getProp()
{
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->getProp();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.