【问题标题】:Create an object from the current class in a static method - PHP在静态方法中从当前类创建一个对象 - PHP
【发布时间】:2016-04-08 00:26:17
【问题描述】:

我的模型类和其他类有一些问题,所以我做了这个简单的例子来解释我的问题:

class person{

  public static $a = "welcome";

  public function __construct(){
                               }

  public static function getobject()
  {
      $v = new person();
      return $v;
  }

}

class student extends person{

  public static $b = "World";

}

$st = student:getobject();//this will return person object but I want student object

echo $st->$b; // There is an error here because the object is not student

所以我想知道写什么而不是$v = new person(); 来获取最后一个继承类的对象。

【问题讨论】:

    标签: php class oop inheritance


    【解决方案1】:

    使用late static bindingstatic 关键字。

    public static function getobject()
    {
        $v = new static();
        return $v;
    }
    

    因此,使用student::getobject(),您将获得student 的实例。

    要检索静态(但为什么呢?)$b 属性,您可以使用$st::$b,或者简单地使用student::$b

    【讨论】:

    • ahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh,静态做了什么,静态和类名之间的关系是什么,无论如何,谢谢,它正在工作,我会把你的答案标记为5分钟后更正一个,因为我现在不能这样做:)因为网站规则
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    相关资源
    最近更新 更多