Php 用相同的函数扩展类

Php 用相同的函数扩展类,php,codeigniter,Php,Codeigniter,如果我有一个类有一个索引函数,我扩展它并创建另一个索引函数。扩展中的索引函数会覆盖父索引函数吗?另外,parent::_construct()在构造的第二个类中到底做了什么 class someclass { public function index() { //do something } } class newclass extends someclass { function __construct() { par

如果我有一个类有一个索引函数,我扩展它并创建另一个索引函数。扩展中的索引函数会覆盖父索引函数吗?另外,parent::_construct()在构造的第二个类中到底做了什么

class someclass
{
    public function index()
    {
        //do something
    }
}

class newclass extends someclass
{
    function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        //do something
    }
}

你可以做一些简单的测试

echo "<pre>";
$b = new B();
$b->index();

echo PHP_EOL;

$c = new C();
$c->index();

代码的工作方式如下:

因此,只有在从
newClass
调用
index()
时,newClass中的
index()
方法才会覆盖某个类中的
index()
方法

要回答第二个问题,调用
newClass
时,
parent::u construct()
将从
someClass
调用构造类

如果我有一个类有一个索引函数,我扩展它并创建另一个索引函数。扩展中的索引函数会覆盖父索引函数吗

对。如果需要,您需要在
newclass::index
的定义中调用
parent::index()

另外,parent::_construct()在构造的第二个类中到底做了什么

class someclass
{
    public function index()
    {
        //do something
    }
}

class newclass extends someclass
{
    function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        //do something
    }
}
这将导致一个PHP错误,因为您没有在父类中定义
\u构造
方法


如果您不确定父类是否有方法(在a中为f.ex.),您可以使用
is\u callable('parent::method')

在方法内部检查它,您可以很容易地通过从两个函数回显一些东西来测试这一点。是的,我想这只是懒惰。
class A {

    function __construct() {
        echo __CLASS__, ".", __METHOD__, PHP_EOL;
    }

    public function index() {
        echo __CLASS__, ".", __METHOD__, PHP_EOL;
    }
}
class B extends A {

    function __construct() {
        parent::__construct();
    }

    public function index() {
        echo __CLASS__, ".", __METHOD__, PHP_EOL;
    }
}
class C extends A {

    public function index() {
        parent::index();
        echo __CLASS__, ".", __METHOD__, PHP_EOL;
    }
}
$someClass = new someClass;
$newClass = new newClass;

$someClass->index(); //this will output what is written in the index function found in someClass
$newClass->index(); //this will output what is written in the index function found in newClass