【问题标题】:return the extending class instance from an abstract method in PHP从 PHP 中的抽象方法返回扩展类实例
【发布时间】:2015-10-27 18:18:50
【问题描述】:
我有一个扩展抽象类的类。
PHP 是否允许从抽象方法中访问扩展类的实例?
类似:
abstract class Foo{
protected function bar(){
return $this;
}
}
class Bar extends Foo{
public function foo(){
// this should hold Bar instance and not Foo's
$barClassInstance = $this->bar();
}
}
$barClassInstance 将保存 Bar 类实例,而不是抽象的 Foo 实例?
【问题讨论】:
标签:
php
oop
inheritance
abstract-class
【解决方案1】:
尝试一千个 stackoverflow 问题值得一试
<?php
abstract class Foo{
protected function bar(){
echo 'Foo', PHP_EOL;
var_dump($this);
return $this;
}
}
class Bar extends Foo{
public function foo(){
echo 'Bar', PHP_EOL;
var_dump($this);
// this should hold Bar instance and not Foo's
$barClassInstance = $this->bar();
var_dump($barClassInstance);
}
}
$bar = new Bar();
$bar->foo();
输出https://3v4l.org/b73bt
Bar
object(Bar)#1 (0) {
}
Foo
object(Bar)#1 (0) {
}
object(Bar)#1 (0) {
}
$this 是对实例的引用,无论它实际上是哪个子类的实例。没有Foo 实例,因为Foo 无法实例化,它是抽象的。即使Foo 是一个具体的类,你也不会有Foo $this 和Bar $this 在同一个对象中。您将只有 $this 指向已创建的特定子类。