繁体   English   中英

在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但是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};

这里有几个问题:

  1. 静态属性$property_one在类B声明, A类的构造函数将无法访问该属性,也不能保证该属性存在。
    当然,自PHP 5.3起,就支持后期静态绑定,但这并不能改变这样一个事实,即您永远不会确保某些静态属性被恰好称为$this->property分配。 如果分配了对象怎么办? 一个int还是float?
  2. 您可以像这样访问静态属性: static::$properyself::$property 注意$ 当您编写static::$this->property ,您希望它的计算结果为self::property_one 您显然缺少$符号。
    您至少需要的是self::${$this->property} 查看有关变量变量的PHP手册。
  3. 您正在尝试从构造函数中返回字符串,这是不可能的。 构造函数must必须返回该类的实例。 没有的任何return语句将被忽略。

要访问构造函数中子类的静态属性,您只能依靠子构造函数:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM