PHP多类继承

时间:2017-10-11 18:51:32

标签: php inheritance

我的情况是我有三个班级:

<?php 
class A {
    protected a_val = 'some_val';
    public function read_a_val( return $this->a_val; );
}

class B extends A {
    protected b_val = 'some_val_2';
    public function read_b_val( return $this->b_val; );
}

class C extends B {
    protected c_val = 'some_val_3';
    public function read_c_val( return $this->c_val; );
    public function c_read_a_val( return $this->a_val; );
}

$obj = new C;
$val = $obj->read_a_val();   // <-- throws error; undefined method
$val = $obj->a_val;          // <-- throws error; cannot access protected property
$val = $obj->c_read_a_val();  // works.
?>

我做错了什么? PHP支持多级继承......我缺少什么?似乎C内部可以访问父(s),没问题,但变量$ obj不能。 $ obj是否应该能够访问A的继承内容(也受保护)?注意:使用PHP v5.6.25

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

<?php 
class A {
    protected $a_val = 'some_val';
    function read_a_val(){ return $this->a_val; }
}

class B extends A {
    protected $b_val = 'some_val_2';
function read_b_val(){ return $this->b_val; }
}

class C extends B {
    protected $c_val = 'some_val_3';
function read_c_val(){ return $this->c_val; }
    function c_read_a_val(){ return $this->a_val; }
}

$obj = new C;
$val1 = $obj->read_a_val();
$val2 = $obj->c_read_a_val(); 

var_dump($val1, $val2);

您用来编写代码的语法完全错误。定义方法的正确方法如下:

function read_a_val(){ return $this->a_val; }

//See the curly braces in the above code and none here.
public function read_a_val( return $this->a_val; );

同样,php中的所有变量都应以$开头$a_val而不是a_val。并且protected属性在类及其子类之外不可用。

查看以下网页:VisibilityA simple tutorialOOP Basics