return PHP 中抽象方法的扩展 class 实例
return the extending class instance from an abstract method in PHP
我有一个扩展摘要 class 的 class。
PHP 是否允许从抽象方法中访问扩展 class 的实例?
类似于:
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 class 实例,而不是抽象的 Foo 实例?
试一试值得一千个 Whosebug 问题
<?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();
Bar
object(Bar)#1 (0) {
}
Foo
object(Bar)#1 (0) {
}
object(Bar)#1 (0) {
}
$this
是对实例的引用,而不管它实际上是哪个 subclass 的实例。没有 Foo
实例,因为 Foo
无法实例化,它是抽象的。即使 Foo
是一个具体的 class,您也不会在同一个对象中有 Foo
$this
和 Bar
$this
。您将只有 $this
指向已创建的特定子 class。
我有一个扩展摘要 class 的 class。 PHP 是否允许从抽象方法中访问扩展 class 的实例?
类似于:
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 class 实例,而不是抽象的 Foo 实例?
试一试值得一千个 Whosebug 问题
<?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();
Bar
object(Bar)#1 (0) {
}
Foo
object(Bar)#1 (0) {
}
object(Bar)#1 (0) {
}
$this
是对实例的引用,而不管它实际上是哪个 subclass 的实例。没有 Foo
实例,因为 Foo
无法实例化,它是抽象的。即使 Foo
是一个具体的 class,您也不会在同一个对象中有 Foo
$this
和 Bar
$this
。您将只有 $this
指向已创建的特定子 class。