【问题标题】:PHP OOP inheritance orderPHP OOP 继承顺序
【发布时间】:2014-09-12 18:33:59
【问题描述】:

为什么子类不在父类构造方法中?当我运行$obj = new C();时,我应该做些什么改变才能让A、B、C的构造函数按顺序执行@

<?php

class A
{

    function A()
    {
        echo "I am the constructor of A. (Grand Parent)<br />\n";
    }
}

class B extends A
{

    function B()
    {
        echo "I am the constructor of B. (Parent)<br />\n";
    }
}

class C extends B
{

    function C()
    {
        echo "I am the constructor of C. (Child)<br />\n";
    }
}

$obj = new C();
?>

【问题讨论】:

    标签: php oop


    【解决方案1】:

    首先:您正在为您的类使用不推荐使用的语法。您应该为构造函数使用__construct() 函数。

    其次,如果在子构造函数中定义了父构造函数,PHP 不会隐式调用它。这意味着您需要自己调用它。

    结合这两个想法,我们得到:

    <?php
    
    class A
    {
       function __construct()
        {
            echo "I am the constructor of A. (Grand Parent)<br />\n";
        }
    }
    
    class B extends A
    {
        function __construct()
        {
            echo "I am the constructor of B. (Parent)<br />\n";
            parent::__construct();
        }
    }
    
    class C extends B
    {
        function __construct()
        {
            echo "I am the constructor of C. (Child)<br />\n";
            parent::__construct();
        }
    }
    
    $obj = new C();
    ?>
    

    PHP 参考是here。请注意,旧语法与 PHP 5.3.3 以后的命名空间类存在兼容性问题。您应该更改新代码的语法。

    【讨论】:

      【解决方案2】:

      您需要像 parent::__construct(); 这样显式调用父类构造函数。所以现在你可以在 C 类中调用 B 类构造函数,在 B 类中调用 A 类构造函数。 希望对您有所帮助:)

      【讨论】:

        【解决方案3】:

        您需要显式调用父级的构造函数。

        <?php
        
        class A
        {
        
            function A()
            {
                echo "I am the constructor of A. (Grand Parent)<br />\n";
            }
        }
        
        class B extends A
        {
        
            function B()
            {
                A::__construct();   // Like this
                echo "I am the constructor of B. (Parent)<br />\n";
            }
        }
        
        class C extends B
        {
        
            function C()
            {
                B::__construct();   // Like this
                echo "I am the constructor of C. (Child)<br />\n";
            }
        }
        
        $obj = new C();
        ?>
        

        您可以找到一些解决方法here

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-02-11
          • 1970-01-01
          • 1970-01-01
          • 2013-02-19
          • 2016-06-25
          • 2018-05-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多