【问题标题】:Object-oriented PHP: Why "this" keyword is a variable?面向对象的 PHP:为什么“this”关键字是变量?
【发布时间】:2014-02-16 09:09:03
【问题描述】:

我现在正在学习 PHP,并注意到来自the tutorial 的一个奇怪事实:

注意:$this 是一个特殊的变量,不能赋值。

不能赋值的对象不是必须实现为常量,而不是变量

为什么会这样?

【问题讨论】:

  • 变量,$this总是指不同的对象。他们本可以将其设为像__FILE__ 这样的magic 常量,但他们没有。嗯,那是 PHP。在许多语言中确实是一样的,其他人使用self,这与其他变量(如foo)无法区分......没有什么必须以某种方式实现,语言设计者可以做随心所欲。

标签: php oop this


【解决方案1】:

The scope of a constant is global。相反,$this 在整个应用程序中发生变化,因为它取决于上下文(即类)。

考虑这个简短的例子:

   class A {
       function printThis() { echo $this; }
   }

   class B {
       function printThis() { echo $this; }
   }

显然,class B 中的$thisclass A 中的$this 不同,因此根据定义它不能是常量*。

*) 编辑: 但是,在 PHP 中存在 magic constants,它会根据上下文而变化:

<?php
$line1 =  __LINE__;
$line2 =  __LINE__;
assert($line1 == $line2);  // fails

所以我认为用户 deceze summarized it pretty well in the comments:“嗯,那是 PHP。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多