【问题标题】:Php multiple class extend onephp多类扩展一
【发布时间】:2014-08-22 13:43:18
【问题描述】:

可以扩展php类(多个类扩展一个)。

--init.php------

include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/functions.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/template.php';
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/debug.php';

-----Functions.php-----

    class Functions{
         // content here
      }

-----模板.php------

    class Template extends Functions{
          public $sTitle = "";

          public function setTitle($title){$this->sTitle = $title;}
        }

--debug.php------

class debug extends Functions{
        // content here
            }

Functions:Template->setTitle('my title');

如果您知道更好的方法,请与我分享。 (这些类位于“类函数”文件包含的不同文件中)

【问题讨论】:

  • 如果真的想伪造多重继承,可以使用魔术函数__call().
  • 许多类可以扩展同一个类。类不能扩展多个。
  • 一个更好的方法来做什么?这是无效的代码,并且没有您所期望的描述。此外,class Functions 的代码味道非常很糟糕。
  • 只是指出:“类不能扩展多个”,但类可以使用许多特征(PHP 5.4)。但是,我不推荐这种方法。仅当您知道自己在做什么时才使用它。

标签: php function class object extends


【解决方案1】:

当然可以。实际上,您可以使用minimal compiling example 测试自己:

<?php

class SuperClass {

  public function __construct(){ echo 'I am the common superclass.  '; }
}

class LittleClass extends SuperClass{}
class LittleLittleClass extends SuperClass{}

new LittleClass();
new LittleLittleClass();

除此之外,调用类Functions 闻起来很像非常糟糕的设计。如果您想在代码库中包含通用功能,请考虑将它们收集到继承链之外的其他位置。

【讨论】:

    【解决方案2】:

    您可以包含对超类没有任何作用的函数 setTitle()(在您的情况下为函数)。然后在模板中你可以覆盖它的功能。在这种情况下,在“调试”类上运行这个函数是安全的。即

    ----init.php------
    
    include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/functions.php';
    include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/template.php';
    include_once $_SERVER['DOCUMENT_ROOT'].'/lib/php/debug.php';
    
    -----Functions.php------
    
        class Functions{
             // content here
        public function setTitle($title){}
          }
    
    -----Template.php------
    
        class Template extends Functions{
              public $sTitle = "";
    
              public function setTitle($title){$this->sTitle = $title;}
            }
    
    -----debug.php------
    
    class debug extends Functions{
            // content here
                }
    
    Functions:Template->setTitle('my title');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-11
      • 2013-06-14
      • 2015-06-19
      • 2012-06-27
      • 2012-07-31
      • 2013-02-06
      • 2017-01-09
      • 2016-05-09
      相关资源
      最近更新 更多