Kha*_* Bz 1 php oop inheritance class
我的模型类和其他类有一些问题,所以我做了这个简单的例子来解释我的问题:
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
Run Code Online (Sandbox Code Playgroud)
所以我想知道要写什么来$v = new person();获取最后一个继承类的对象。
使用后期静态绑定的static关键字。
public static function getobject()
{
$v = new static();
return $v;
}
Run Code Online (Sandbox Code Playgroud)
所以,student::getobject()你得到了一个实例student。
要检索静态(但为什么?)$b属性,您可以执行$st::$b, 或简单地执行student::$b。