“自我”如何在继承的类中完全起作用? [英] How does 'self' exactly work in inherited classes?

查看:98
本文介绍了“自我”如何在继承的类中完全起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

According to php, class::self always points to the class itself, but as I wrote down these codes, something strange happens:

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 并不完全继承到孩子,它的工作原理更喜欢这个:

It means that the self in parent class does NOT exactly inherit into the child, it works more like to this:

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

这是php的功能还是bug?或者是这样的意思吗?

Is that a feature from php or is it a bug? Or is it mean to be like this?

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

Otherwise, such thing is occurred as I tried to tell a class create objects from itself, the code is something like this:

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

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

class Something extends Models {...}

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

也许有人会问,为什么不设置值为的变量? class ,并将变量用作__construction函数?

Maybe someone would ask, "why don't you set a variable with the value of class, and use the variable as the __construction function?"

像这样:

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

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

In fact I did that, and got a even more weird result:

只有当班级没有任何属性或功能但<$> c $ c> find(),或者告诉我一个变量显示函数存在的位置的错误会跳出来。

It works only when the class does not have any property or function but find(), or an error telling me a variable shows off where a function sould exist would jump out.

推荐答案

在PHP中,类不是对象。因此,没有静态方法的继承(实际上,它们与全局函数类似)。

In PHP, classes are not object. Because of that, there is no inheritance of static methods (actually, they are similar to global functions).

所以,当C_foo说自我时,它总是意味着C_foo(即使你从C_bar调用了一个方法)。

So, when C_foo says self, it always means C_foo (even if you called a method from C_bar).

如果要从抽象类方法创建实例,则应尝试使用Factory模式。

If you want create instances from an abstract class method, you should try the Factory pattern.

这篇关于“自我”如何在继承的类中完全起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆