无法调试输出


unable to debug the output

今天我正在阅读设计模式,我试图制作一个示例程序,它包含一个接口,两个实现该接口的类和一个主索引类。首先是界面

<?php 
interface Iproduct 
{
    //Define the abstract method
    public function apple();
    public function mango();    
}

实现接口的两个类

<?php 
// Including the interface
include_once 'Iproduct.php';
    class Apple implements Iproduct 
    {
        public function apple()
        {
            echo ("We sell apples!");
        }   
        public function mango()
        {
            echo ("We do not sell Mango!");
        }
    }
<?php
// Include the interface Iprodduct
include_once 'Iproduct.php';
class Mango implements Iproduct
{
    public function apple()
    {
        echo ("We do not sell Apple");
    } 
    public function mango()
    {
        echo ("We sell mango!");    
    }
}

现在是主类

<?php
include_once ('apple.php');
include_once ('Mango.php');
class UserProduct
{
    public function __construct()
    {
        $apple_class_obj=new Apple();
        $mango_class_obj=new Mango();
        //echo("<br/> the apple class object: ".$apple_class_obj);
    }   
}
//creating the object of the UserProduct
echo ("creating the object!<br/>");
$userproduct_obj=new UserProduct();
?>

执行代码时得到的输出是:

creating the object!
we sell apples!we sell mango

现在的问题是我无法理解第二个输出如何,即,我们卖苹果!我们卖芒果!正在显示。请让我知道原因

过去(PHP 版本 5 之前(,在创建对象时调用与类同名的方法(PHP 旧式构造函数方法(。

因为 PHP 向后兼容该行为,所以您现在可以看到输出。

为了向后兼容,如果 PHP 5 找不到给定类的 __construct() 函数,并且该类没有从父类继承一个函数,它将按类的名称搜索旧式构造函数。实际上,这意味着唯一会出现兼容性问题的情况是,如果类具有名为 __construct() 的方法,该方法用于不同的语义。[我加粗]

来自:PHP 手册中的构造函数和析构函数

因此,您遇到的不是界面或对象本身的问题,而只是您可能没有意识到的一些副作用(这真的很旧(。

若要解决此问题,只需在两个类中实现一个 __construct() 方法,以便不再调用旧式构造函数:

class Mango implements Iproduct
{
    public function __construct() {}
    ...

每个类的空方法在这里足以阻止这种情况。


您可能也对以下内容感兴趣:

  • 函数 __construct(( 是做什么用的?(2009年1月(
  • 为什么 PHP 中的函数和方法不区分大小写?(2010年5月(
  • 为什么即使类和构造函数大小写不同,仍然调用我的构造函数? (2011年10月(

在 PHP 4x 中,与类同名的方法被视为构造函数。使用 php 5x 时,构造函数被显式命名为 __construct

由于 PHP 的向后兼容性,您体验到的结果。