从A类的B类(扩展了A类)调用静态方法 [英] Calling Static Method from Class B(which extends Class A) of Class A

查看:142
本文介绍了从A类的B类(扩展了A类)调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实践测试中有一个有趣的问题,我不知道答案.以下代码的输出是什么?

There was an interesting question in a practice test that I did not understand the answer to. What is the output of the following code:

<?php
class Foo {
    public $name = 'Andrew';

    public function getName() {
        echo $this->name;
    }
}

class Bar extends Foo {
    public $name = 'John';

    public function getName() {
        Foo::getName();
    }
}

$a = new Bar;
$a->getName();
?>

最初,我认为这会产生错误,因为静态方法无法引用$ this(在PHP5中至少).我自己对此进行了测试,它实际上输出了John.

Initially, I thought this was produce an error because static methods can not reference $this (atleast in PHP5). I tested this myself and it actually outputs John.

我添加了Foo :: getName();在脚本的末尾,并确实得到了我所期望的错误.那么,当您从扩展了您所调用的类的类中调用静态方法时,会发生什么变化呢?

I added Foo::getName(); at the end of the script and did get the error I was expecting. So, what changes when you call a static method from within a class that extends the class you're calling from?

有人介意详细解释这里发生了什么吗?

Would anyone mind explaining in detail exactly what is going on here?

推荐答案

$ this到在其上下文中调用了该方法的对象.因此:$ this是$ a-> getName()是$ a. $ fooInstance-> getName()中的$ this将是$ fooInstance.如果设置了$ this(在对象$ a的方法调用中)并且我们调用了静态方法,则$ this仍将分配给$ a.

$this to the object in whose context the method was called. So: $this is $a->getName() is $a. $this in $fooInstance->getName() would be $fooInstance. In the case that $this is set (in an object $a's method call) and we call a static method, $this remains assigned to $a.

使用此功能可能会引起很多混乱. :)

Seems like quite a lot of confusion could come out of using this feature. :)

这篇关于从A类的B类(扩展了A类)调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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