PHP:extends 继承测试

官网信息:一个类可以在声明中用 extends,关键字继承另一个类的方法和属性。PHP不支持多重继承,一个类只能继承一个基类。

被继承的方法和属性可以通过用同样的名字重新声明被覆盖。但是如果父类定义方法时使用了 final,则该方法不可被覆盖。可以通过 parent:: 来访问被覆盖的方法或属性。

当覆盖方法时,参数必须保持一致否则 PHP 将发出 E_STRICT 级别的错误信息。但构造函数例外,构造函数可在被覆盖时使用不同的参数。


子类在继承父类后,会拥有父类的属性和方法


test_a.php

<?php

class test_a
{
    public $name_a='name_a';
    public function get_a(){
        echo 'test_a<br/>';
    }
}


test_b.php

<?php
require_once 'test_a.php';
class test_b extends test_a
{
    public function get_b(){
        echo 'get test_b<br/>';
    }
    public function call_b(){
        echo 'call test_b<br/>';
    }
    public function get_a(){
        parent::get_a();
        echo '^^^^test_b->get_pa()<br/>';
    }
}

测试
test.php
<?php
require_once 'test_b.php';
require_once 'test_a.php';
//实例化对象test_b
$b = new test_b();
//调用对象test_a中的成员方法get_a
$b->get_a();//继承了父类允许继承的方法
//给对象test_a中的成员属性赋值
$b->name_a=1;//继承了父类允许继承的属性
//调用对象test_b中的成员方法get_b
$b->get_b();
//调用对象test_b中的成员方法call_b
$b->call_b();
//调用对象test_b中的成员方法get_pa
$b->get_a();//在子类方法get_a()中调用父类的get_a()方法

//结果
/*test_a
get test_b
call test_b
test_a
^^^^test_b->get_pa()*/

//实例化对象test_a
$a = new test_a();
//调用对象test_a中的成员方法get_a
$a->get_a();
//给对象test_a中的成员属性赋值
$a->name_a=1;
//调用对象test_b中的成员方法get_b
//$a->get_b();
//调用对象test_b中的成员方法call_b
//$a->call_b();

//结果
/*
 * test_a
 * 报错:Call to undefined method test_a::get_b()
 * 原对象的调用可以
 * $a->get_a();
 * $a->name_a=1;
 * 对象test_b的无法调用
 * $a->get_b();
 * $a->call_b();
 * */


 

猜你喜欢

转载自blog.csdn.net/root_admin_12138/article/details/81213265