批改状态:合格
老师批语:

类自定加载器
<?phpspl_autoload_register(function($className) {echo $className."<br/>";// $file = __DIR__.'\\controller\\'.str_replace('\\',DIRECTORY_SEPARATOR,$className).'.php';$file = "..\\oop\\MyClass\\".str_replace('\\',DIRECTORY_SEPARATOR,$className).'.php';if(!(is_file($file) && file_exists($file))){throw new \Exception("类 - 文件名不合法或文件不存在");}require $file;});
Person 类
<?phpclass Person{// 父类属性public $Name;private $Age;protected $Job;public static $Count;// 父类构造方法public function __construct($name,$age,$job){$this->Name = $name;$this->Age = $age;$this->Job = $job;}function getAge(){return $this->Age;}function setAge($age){$this->Age = $age;}function show(){echo "这是父类Person的show方法<br />";}}
Man类,继承自Person
<?phpclass Man extends Person{//子类自有属性public $Shenggao;//重写父类构造方法public function __construct($name,$age,$job,$shengao){parent::__construct($name,$age,$job);$this->Shenggao = $shengao;self::$Count += 1;}// 重写父类show方法,同时调用父类的show方法public function show(){parent::show();echo '这是子类重写父类show方法';}public function staticCount(){echo '这是静态Person类的静态属性值:'.self::$Count;}}
Client
<?phprequire 'autoLoad.php';$liu = new Man("刘德华",59,"歌手演员",180);$zhang = new Man("张学友",56,"歌手演员",182);$liu->show();//父类的show方法echo '<pre>';var_dump($liu);var_dump($zhang);// 通过对方访问方法,访问父类私有属性$liu->setAge(60);echo '通过对方访问方法,访问父类私有属性:'.$liu->getAge();echo '<br />';echo $liu->staticCount();
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号