【问题标题】:unable to debug the output无法调试输出
【发布时间】:2013-08-08 13:31:36
【问题描述】:

今天我正在阅读设计模式,我尝试制作一个示例程序,它由一个接口、两个实现该接口的类和一个主索引类组成。让我们看看下面给出的代码。 首先是Iproduct接口

<?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 oop design-patterns


    【解决方案1】:

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

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

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

    发件人:Constructors and Destructors in the PHP Manual

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

    要解决这个问题,只需在两个类中实现 __construct() 方法,这样旧式构造函数就不会再被调用:

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

    每个类一个空方法就足够了。


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

    【讨论】:

    • 谢谢你为了防止它我应该做什么......意味着我应该做些什么改变
    • 我为您添加了一些简单的示例并描述了如何轻松解决该问题。如果现在更清楚,请告诉我。
    • 我明白了你所解释的一切非常感谢......因为我正在切换到 oops 概念所以......我是新手。谢谢
    • 没问题,如果您到目前为止还不知道构造函数 是什么,也可以了解一下。这是 OOP 中的一个常见概念,并非 PHP 中的 OOP 所特有的。
    【解决方案2】:

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

    您因 PHP 向后兼容而体验到的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-16
      相关资源
      最近更新 更多