Jun 2

PHP5中类的继承、实现等关系研究 不指定

Handy , 14:24 , PHP研究 , 评论(0) , 引用(0) , 阅读(743) , Via 本站原创 | |
1.接口的抽象实现类中不能出现在接口中声明的函数的抽象实现。
太绕口了,请看以下例子:

<?php

interface ITest
{
    function Fun();
}

abstract class AbstractTest implements ITest
{
    abstract public function GetA();          // OK!
    
    abstract public function Fun();          // Fatal error: Can't inherit abstract function ITest::Fun() (previously declared abstract in AbstractTest)
}
?>


实际上就是说,抽象类中的抽象函数只能是自己“原创的”,如果在他需要实现的接口中已经出现同名的函数,那么在这个抽象类中,这个函数就不能是抽象的。如果我们必须要使用这种实现方式,那应该怎么办呢?请看下面的例子:


<?php

interface ITest
{
    function Fun();
}

abstract class AbstractTest implements ITest
{
    abstract public function GetA();         // OK!
   // Ignore function "Fun" here!
}

class TestO1 extends AbstractTest
{
    public function __construct()
    {
        print "TestO1:__construct();\r\n";
    }
    
    public function Fun()
    {
        print "TestO1:Fun();\r\n";
    }
}




$obj = new TestO1();
$obj->Fun();                                    // TestO1:__construct(); TestO1:Fun1();
?>


2.子类中的函数直接覆盖父类中的同名函数(构造函数也遵循此法则)
请看如下示例:

<?php

interface ITest
{
    function Fun();
}

abstract class AbstractTest implements ITest
{
    public function __construct()
    {
        print "AbstractTest:__construct();\r\n";
    }

    public function Fun()
    {
        print "AbstractTest:Fun();\r\n";
    }
}

class TestO2 extends AbstractTest
{
    public function Fun()                      // Overwrite!
    {
        print "TestO2:Fun();\r\n";
    }
}



$obj = new TestO2();
$obj->Fun();                                  //AbstractTest:__construct(); TestO2:Fun();
?>


如果还需要执行父类中的同名函数,那么就要使用关键字parent。例如,上面的例子我们修改一下变成:

<?php

interface ITest
{
    function Fun();
}

abstract class AbstractTest implements ITest
{
    public function __construct()
    {
        print "AbstractTest:__construct();\r\n";
    }

    public function Fun()
    {
        print "AbstractTest:Fun();\r\n";
    }
}

class TestO2 extends AbstractTest
{
    public function Fun()                      // Overwrite!
    {
        parent::Fun();                          // Call function in parent
        print "TestO2:Fun();\r\n";
    }
}



$obj = new TestO2();
$obj->Fun();                                  // AbstractTest:__construct(); AbstractTest:Fun(); TestO2:Fun();
?>



Tags: , ,
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]