parent :: method()-调用非静态方法 [英] parent::method() - calling non static method

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

问题描述

我不了解在PHP中调用父方法的概念. 父方法不是静态的,但会被静态调用-通常,PHP会引发错误/警告.

I don't understand the concept of calling a parent method in PHP. The parent method is not static, yet it is called statically - normally PHP would throw an error/warning.

问题是,这是PHP的一个怪癖,还是在OOP中应该是这样?

以php.net为例:

Taking the example from php.net:

<?php
class A {
    function example() {
        echo "I am A::example() and provide basic functionality.<br />\n";
    }
}

class B extends A {
    function example() {
        echo "I am B::example() and provide additional functionality.<br />\n";
        parent::example();
    }
}

$b = new B;

// This will call B::example(), which will in turn call A::example().
$b->example();
?>

http://php.net/manual/en/keyword.parent.php

在PHP 5中,调用非静态方法静态生成E_STRICT 液位警告.

In PHP 5, calling non-static methods statically generates an E_STRICT level warning.

http://php.net/manual/en/language.oop5. static.php

推荐答案

如果您要查看

If you will look at the definition of static method you will see:

  1. 静态方法旨在与类的所有实例相关,而不是与任何特定实例相关.-实际上,此方法与父类的所有子级都相关.
  2. 即使该类的实例尚不存在,也可以调用静态方法.-同样,您永远不会创建父类的实例来调用该方法.
  1. Static methods are meant to be relevant to all the instances of a class rather than to any specific instance. - indeed this method is relevant to all children of the parent class.
  2. A static method can be invoked even if no instances of the class exist yet. - again, you never create an instance of the parent class to invoke the method.

因此,我们可以将此参数作为 PHP 的借口.顺便说一下,在 C ++ 中,它是通过相同的方式完成的.

So we can take this argument as an excuse for PHP. By the way, in C++ it is done the same way.

但是还有其他语言,就像您所说的那样.例如,在 JAVA 中,称为super.printMethod();的父方法在 C#中类似于base.printMethod().

But there are other languages, where it is done like you said. For example, in JAVA, the parent method called like super.printMethod();, in C#, it is done like base.printMethod().

因此在 PHP 中,为简化解析器可能会这样做,因为对于这种调用parent->printMethod(),它们将需要特定的边沿大小写.

So in PHP it might be done for the parser simplicity, as they will need a specific edge case for such invocation parent->printMethod().

这篇关于parent :: method()-调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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