繁体   English   中英

使用静态方法从当前类创建对象-PHP

[英]Create an object from the current class in a static method - PHP

我的班级Model和其他班级存在一些问题,因此我举了一个简单的例子来说明我的问题:

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(); 获取最后继承的类的对象。

使用Late static bindingstatic关键字。

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

因此,使用student::getobject()可以获取student的实例。

要获取静态(但为什么呢)的$b专有性,您可以执行$st::$b ,或者简单地执行student::$b

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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