在 php 中调用另一个类中的静态属性


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但输出只是__construct中参数输入的名称;

当我print_r( static::$this->property );时,输出只是property_one

只需更改:

return static::$this->property;

跟:

return static::${$this->property};

也许是这样的?

<?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. 静态属性$property_one在类 B 中声明,A类的构造函数将无法访问该属性,也不能保证此属性存在。
    当然,从 PHP 5.3 开始,支持后期静态绑定,但这并不能改变这样一个事实,即你永远无法确定某些恰好被调用的静态属性恰被分配$this->property。如果为其分配了一个对象怎么办?整数,还是浮点数?
  2. 您可以访问如下所示的静态属性:static::$properyself::$property。请注意$!当你写static::$this->property时,你期望它的计算结果是self::property_one。你显然错过了$标志。
    您至少需要的是 self::${$this->property} .查看有关变量的 PHP 手册。
  3. 您正在尝试从构造函数返回字符串,这是不可能的。构造函数必须返回类的实例。任何不这样做的返回语句都将被忽略。
要访问构造函数中子类的

静态属性,您只能依赖子类的构造函数:

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();