gpt4 book ai didi

php - 'self' 在继承类中究竟如何工作?

转载 作者:IT王子 更新时间:2023-10-29 00:11:58 28 4
gpt4 key购买 nike

根据 php,class::self 总是指向类本身,但是当我写下这些代码时,发生了一些奇怪的事情:

class C_foo{
function foo() { return "foo() from C_foo"; }
function bar() { echo self::foo(); }
}

class C_bar extends C_foo{
function foo() { return "foo() from C_bar"; }
}

C_foo::bar();
C_bar::bar();

我认为输出应该是:

foo() from C_foo
foo() from C_bar

但实际上:

foo() from C_foo
foo() from C_foo

这意味着父类中的 self 并没有完全继承到子类中,它更像是这样:

foo() {return parent::foo();}

这是 php 的一个特性还是一个错误?还是故意这样?

否则,当我试图告诉类从自身创建对象时,会发生这样的事情,代码是这样的:

class Models {
function find($exp) {
...
...

$temp_model = new self();
...
...
}
}

class Something extends Models {...}

$somethings = Something::find("...");

也许有人会问,“为什么不设置一个值为class的变量,并将该变量作为__construction函数呢?”

像这样:

...
...
function find($exp) {
...
...
$class_name = __class__;
$temp_model = new $class_name();
...
...
}
...

事实上,我这样做了,得到了一个更奇怪的结果:

只有当类除了find() 没有任何属性或函数时,或者告诉我一个变量显示函数应该存在的地方的错误时,它才会跳出。

最佳答案

听起来您在描述称为“后期静态绑定(bind)”的 PHP 功能。

PHP 提供了两种语法:self::static::

static 是在 PHP 5.3 中引入的,因为很多人都希望 self 能够像您描述的那样工作。

有关更多信息,请参阅 PHP 手册:http://php.net/manual/en/language.oop5.late-static-bindings.php

您还可以使用语法 new self()new static() 来创建新实例:

$parent = new self();
$child = new static();

关于php - 'self' 在继承类中究竟如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10131786/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com