【问题标题】:Late static bindings后期静态绑定
【发布时间】:2012-09-27 14:22:29
【问题描述】:

我们是否需要在以下情况下使用static::$attribute 而不是$this->attribute

b.php

class B {
public function tellAttribute(){
// $this OR static ??
    echo $this->attribute;
}
}

a.php

include 'b.php';

class A extends B {
public $attribute = 'foo';
}

$test = new A();
$test->tellAttribute();

问这个是因为对我来说它不应该工作,除非我使用static::$attribute,但它仍然在呼应foo。是什么原因?

【问题讨论】:

  • 忘掉静态,没有它也没关系,因为这根本不是静态调用。通常没有理由在 PHP 中使用后期静态绑定,它只是一个让一些用户感到困惑的特性。
  • @hakra parent:: 在处理继承自其他类的类时实际上非常有用。
  • 我从 Kevin Yank 那里了解到,我们需要使用 static::attribute 来访问正在继承的类的属性,而 $this 不起作用。
  • @Mahn: parent:: 不是静态的,与后期静态绑定无关。
  • @YousufIqbal Kevin Yank 错了(不管是谁)

标签: php static this


【解决方案1】:

B 类定义了一个名为 tellAttribute() 的公共函数,如下所示:

public function tellAttribute(){
    echo $this->attribute;
}

然后实例化类 A - 类 B 的子类 - 并执行以下操作:

$test = new A();
$test->tellAttribute();

所以,你实例化一个 A 类的对象,然后在这个对象上调用 tellAttribute()。因为tellAttribute() 方法使用$this 变量,所以您指的是您已实例化的实际对象。即使您在B 类(父级)中定义了tellAttribute(),它实际上将指向您拥有公共$attribute 属性的子对象(A 类的实例)。这就是它打印foo 以及您不需要使用static:: 的原因。

另一方面,考虑一下:

class B {
    public static $attribute = 'foo';
    public function tellAttribute(){
        echo self::$attribute; // prints 'foo'
    }
    public function tellStaticAttribute() {
        echo static::$attribute; // prints 'bar'
    }
}

class A extends B {
    public static $attribute = 'bar';
}

$test = new A();
$test->tellAttribute();
print "<BR>";
$test->tellStaticAttribute();

在本例中,我没有使用$this 变量,而是使用self::static::tellAttribute() 具有 self:: 并且将始终打印 foo。这是因为self:: 只能引用当前类。 tellStaticAttribute() 使用 static:: 并将“动态”打印类。我对技术术语等不太了解,所以我会给你一个手册的链接(我想你已经从你的帖子中读过):http://php.net/manual/en/language.oop5.late-static-bindings.php

希望能回答你的问题。

【讨论】:

    【解决方案2】:

    我们是否需要使用 static::$attribute 而不是 $this->attribute 在以下情况:

    ,您绝对不会在您描述的场景中使用static 关键字,并且没有理由起作用。将$this 的上下文视为将所有不同的继承类“加起来”为一个的结果。也就是说,如果class B extends Aclass C extends B,通过实例化C,类A、B和C的所有属性和函数都可以通过类内的$this上下文获得,C完全可以在它自己的函数中使用在 B 中定义的属性,反之亦然,因为一切都在那里,就好像它是您实例中的一个独立类。

    【讨论】:

    • ...除非进一步定义为private
    【解决方案3】:

    是的,它会工作....$attribute 是公开的......而且 A 也继承了 tellAttribute() 我不确定您的期望。

    【讨论】:

    • 对我来说,如果我们在 class B 中使用 $this-&gt;attribute,由于 php 中的早期静态绑定,它会给出未定义属性的错误。
    • Class B 没有扩展任何东西只class A extends B 肯定会有错误
    【解决方案4】:

    您没有在任何地方使用“静态”关键字。您在这里的一般类设置对我来说有点奇怪,但是如果您希望 $attribute 成为静态变量,则需要输入:

     public static $attribute = 'foo';
    

    请记住,静态变量基本上是全局变量,您可以在此处查看更多信息:http://php.net/manual/en/language.oop5.static.php

    【讨论】:

    • 这和late static binding一点关系都没有,除了shared关键字。
    • 一个变量基本上永远不会是一个常量。不!您可能指的是全局变量。
    • 我问你刚才回答了什么吗?
    • 我的意思是您没有进行后期静态绑定,因为您在上面放置的代码中处于非静态上下文中。如果您参考上面 Pete171 帖子中的示例,您可以看到里面的示例。您只是在发布的内容中进行基本继承,因此 $this 没有理由不起作用。
    猜你喜欢
    • 1970-01-01
    • 2011-04-15
    • 2011-02-12
    • 1970-01-01
    • 2012-04-21
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多