这里有什么PHP课程? [英] What is going on here in PHP with classes?

查看:109
本文介绍了这里有什么PHP课程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这段代码,则会回显字符串test。这是在PHP 5.3中。这是不应该依赖的一些疏忽,还是在PHP中实现多重继承的某种方式?

If I have this code, the string "test" is echoed. This is in PHP 5.3. Is this some oversight that shouldn't be relied on, or is it some way of achieving multiple inheritence in PHP?

class Test1
{
    function getName()
    {
        return $this->name;
    }
}

class Test2
{
    public $name = 'test';

    function getName()
    {
        return Test1::getName();
    }
}

$test = new Test2;
echo $test->getName();

编辑:

正如已经指出GZipp的评论这实际上是记录在案的行为。参见本页: http://us2.php.net/manual/en /language.oop5.basic.php 和标题Example#2 $ this伪变量的一些例子。

As has been pointed out the comments by GZipp this is actually documented behaviour. See this page: http://us2.php.net/manual/en/language.oop5.basic.php and the heading "Example #2 Some examples of the $this pseudo-variable".

A类和B类与我上面的两个测试类和行相似的关系

Classes A and B have a similar relationship to my two test classes above and the lines

$b = new B();
$b->bar();

显示与我的例子大致相同的结果。

Show more or less the same result as my example.

推荐答案

PHP允许调用非静态方法,就像它们是静态的一样 - 这是一个特性。 PHP传递 $ this 作为此类调用的隐式参数。就像以正常方式调用方法一样。

PHP allows calling non-static methods as if they were static - that's a feature. PHP passes $this as an implicit parameter to such calls. Much like it does when calling a method the normal way.

但很明显,PHP不会检查静态调用的类是否继承当前类 - 这就是错误。

But obviously PHP doesn't check whether the statically called class inherits the current one - and that's the bug.

这就是你如何看待PHP的作用:

This is how you could think of what PHP does:

function Test1->getName($this = null) {
    return $this->name;
}

function Test2->getName($this = null) {
    return Test1->getName($this);
}

$test = new Test2;
echo $test->getName($test);

这种行为是错误的。正确的 Test2-> getName 将是:

This behavior is wrong. The correct Test2->getName would be:

function Test2->getName($this = null) {
    return $this instanceof Test1 ? Test1->getName($this) : Test1->getName();
}

这篇关于这里有什么PHP课程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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