PHP语言 class 问题 很急!

来源:百度知道 编辑:UC知道 时间:2024/06/08 20:09:44
<?php
// class tree
class Mammal {
public $name;
protected $age;
private $species;

function set_age($age)
{
$this->age=$age;
}
function print_age()
{
echo 'Mammal Age='.$this->age.'<br>';
}
}
class Human extends Mammal {
function print_human_age()
{
echo 'I have lived '.$this->age.' years'.'<br>';
}
}

$mammal = new Mammal;
$mammal->name = 'William'; // ok
$mammal->set_age(3);
$mammal->print_age(3);

$human = new Human;
$human->name = 'Barry'; // ok
$human->set_age(30);
$human->print_age(30);
$human->print_human_age();
$human->age = 1; // fatal error
$human->species = 'Boy'; // undefined
?>

不明白为什么出现fatal error 和unddfined,$age 是protected, 为什么Human是Mammal的子类还不能调用呢?

$age是protected。被human继承后还是protected,protected不可以被访问。所以$human->age = 1;报错是理所当然的。而$species在Mammal中是private,这也是不可访问的。不过,在我的机子(window环境下),$human->species = 'Boy'; 这是不报错的。因为php可以不声明就可以使用变量。可能你用的是linux吧。又或者是你的php环境配置有问题吧