$这在PHP中是动态绑定的,对吧? [英] $this in php is bound dynamically, right?

查看:134
本文介绍了$这在PHP中是动态绑定的,对吧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现错误,因为我认为是因为我在重构中犯了一些错误,但是我找不到关于 $ this 是有约束力的,我的错误可以解释为静态绑定。

I'm getting an error that I think is because I've made some kind of mistake in a refactoring, but I can't find documentation on when $this is bound, and my error could be explained by it being bound statically.

额外积分(我实际上不能给你额外的积分)链接到关于这种事情在php。的优秀文档

Extra points (I can't actually give you extra points) for links to excellent documentation about this kind of thing in php.


我得到的错误告诉我,$ code> Subclass :: $ var 在我做的时候不存在,例如,超级类中的 echo $ this-> var

The error that I'm getting is telling me that Subclass::$var doesn't exist when I do, for example, echo $this->var in a superclass. The $var exists in the subclass, though.

推荐答案

这个工程可以在子类中存在 $ var 在PHP中:

This works in PHP:

class A {
    public function foo() {
        echo $this->bar;
    }
}

class B extends A {
    public $bar = 1;
}

$b = new B;
$b->foo();  // 1

它的工作原理是PHP的动态范围解析(即:范围在运行时而不是编译时间)。然而,我建议反对它,因为它真的是一种语言的特殊性。第二,未能在子类中声明 $ bar 会导致错误。我认为一个类只能引用它所知道的成员。

It works because of the dynamic scope resolution that PHP has (i.e.: scope is resolved at runtime as opposed to compile time). However, I'd recommend against it, because it is really a particularity of the language for one. For second, failing to declare $bar in a subclass would result in an error. I think that a class should only reference members that it is aware of.

相同的代码,用C ++语言表示:

The same code, say in C++:

class A {

public:
    void foo() {
        std::cout << bar;
    }

};

class B : public A {

public:
    int bar;
    B() {
        bar = 1;
    }

};

...会给你一个编译错误(在A :: foo()中: 'bar'未在此范围内声明)。

...would give you a compile error (In A::foo(): 'bar' was not declared in this scope).

这篇关于$这在PHP中是动态绑定的,对吧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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