【问题标题】:PHP 7.4. Instantiation of a class which contains a method of the same name invokes the methodPHP 7.4。包含同名方法的类的实例化调用该方法
【发布时间】:2021-06-10 01:10:29
【问题描述】:

这是一种错误还是什么?从包含与该类同名的方法的类创建对象时,该语句会打印该方法的输出。(PHP 7.4)

<?php
class Y {
    public $name = "Red";
    public function y() {
        echo $this->name;
    }
}
$x = new Y(); // outputs "Red"

函数名不区分大小写,因此该语句输出 y()?

【问题讨论】:

标签: php php-7.4


【解决方案1】:
<?php
class Y {
    public $name = "Red";
    public function y() {
        echo $this->name;
    }
}
$x = new Y(); // outputs "Red"

这是旧式的构造函数。请参阅标题“旧式构造函数”部分。

https://www.php.net/manual/en/language.oop5.decon.php#language.oop5.decon

它本质上与调用__construct 相同,但使用旧样式将导致 PHP 7.4 中的弃用通知

<?php
class Y {
    public $name = "Red";
    public function __construct() {
        echo $this->name;
    }
}
$x = new Y(); // outputs "Red"

附带说明,请确保在开发时打开错误报告。 https://stackoverflow.com/a/21429652/296555

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

【讨论】:

    【解决方案2】:

    我没有收到任何错误(我的错),但它迫使我进入流程的逻辑:

    • 引擎看到“new”关键字并创建一个新对象。
    • 由于函数名不区分大小写,因此该方法被认为是 构造函数。
    • 因此,构造函数创建了一个“Y”的新实例,并立即 回显 y() 中声明的字符串。

    它可以被视为一项功能,但也可以作为deprecation 的正当理由。

    作为对比,类似情况下的JS也不抛出异常:

    class Y {
                constructor() {
                    this.name = "Red";
                }
                Y() {
                    return this.name;
                }
            }
            let x = new Y(); //creates a new instance of Y
            console.log(x.Y()); // outputs "Red"
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 2010-09-17
      • 2012-01-31
      • 2014-12-13
      • 2015-04-26
      • 2013-08-15
      相关资源
      最近更新 更多