为什么 self::function() 和 $self->variable 或 self::$variable 即使有 $this->function() 和 $this->variable (PHP)?
我对这两个关键字以及在 PHP5 中使用它们的方式感到困惑。我认为“this”用于实例化对象(非静态),而“self”指的是对象本身,而不是它的实例,因此在静态对象中使用。正确的?
现在,我相信在类的静态方法中调用另一个静态变量/方法的正确用法如下:
self::doSomething();
self::$testVar;
这是真的吗?
然而,以下情况似乎也是可能的:
$self->testVar;
然而,$testVar 是静态的。这是为什么?
另外,为什么 $ 有时在 self 前面使用,有时不使用,“this”关键字也有同样的问题?
I'm confused about these two keywords and the way to use them in PHP5. I think that "this" is used for instanced objects (not static) while "self" is referring to the object itself, not an instance of it and thus used within static objects. Right?
Now, I believe that the correct use inside a class's static method to call another static variable/method is the following:
self::doSomething();
self::$testVar;
That's true?
However, the following also seems to be possible:
$self->testVar;
Yet, $testVar is static. Why is that?
Also, why is $ used infront of self sometimes and sometimes not, and same question for "this" keyword?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你是对的, self 用于静态自引用,而 $this 用于实例化自引用。 self 和 $this 似乎在任何地方都可以工作,但请考虑一下:
这会导致致命错误,因为 foo() 是静态调用的。最好花一些时间适当地使用它们,而不是总是使用其中之一。
You're right, self is for static self-references while $this is for instantiated ones. self and $this might appear to work everywhere but consider this:
This results in a fatal error because foo() was called statically. It's best to take some time and use them appropriately rather than always using one or the other.
您似乎对此理解正确。 self:: 当您没有可用对象的实例时,用于静态成员和函数,而 $this-> 则用于静态成员和函数。这样做时会使用语法。
因此,在静态方法中,您必须使用 self:: b/c 静态方法就是......静态的,并且可以在没有创建对象实例的情况下调用。 (即 YourClass::staticFunction()) 尽管在非静态方法中使用 $this->memberVar 是完全合乎逻辑的,因为该函数是通过实例化对象调用的。 ($yourClass->nonStaticFunction()) 因此 $this 实际上存在于函数的上下文中。
You seem to be understanding this correctly. self:: is used for static members and functions when you do not have an instance of the object available, while the $this-> syntax is used when you do.
So in a static method, you would have to use self:: b/c the static method is just that... static and could be called without an instance of the object being created. (i.e. YourClass::staticFunction()) It is perfectly logical though to use $this->memberVar in a non-static method as the function is being called through an instantiated object. ($yourClass->nonStaticFunction()) Therefore $this actually exists within the context of the function.