Blogger Information
Blog 34
fans 0
comment 0
visits 20281
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php面向对象之对象成员,静态成员,继承
小庄
Original
567 people have browsed it

php面向对象之对象成员,静态成员,继承


类自定加载器

  1. <?php
  2. spl_autoload_register(function($className) {
  3. echo $className."<br/>";
  4. // $file = __DIR__.'\\controller\\'.str_replace('\\',DIRECTORY_SEPARATOR,$className).'.php';
  5. $file = "..\\oop\\MyClass\\".str_replace('\\',DIRECTORY_SEPARATOR,$className).'.php';
  6. if(!(is_file($file) && file_exists($file))){
  7. throw new \Exception("类 - 文件名不合法或文件不存在");
  8. }
  9. require $file;
  10. });

Person 类

  1. <?php
  2. class Person{
  3. // 父类属性
  4. public $Name;
  5. private $Age;
  6. protected $Job;
  7. public static $Count;
  8. // 父类构造方法
  9. public function __construct($name,$age,$job){
  10. $this->Name = $name;
  11. $this->Age = $age;
  12. $this->Job = $job;
  13. }
  14. function getAge(){
  15. return $this->Age;
  16. }
  17. function setAge($age){
  18. $this->Age = $age;
  19. }
  20. function show(){
  21. echo "这是父类Person的show方法<br />";
  22. }
  23. }

Man类,继承自Person

  1. <?php
  2. class Man extends Person{
  3. //子类自有属性
  4. public $Shenggao;
  5. //重写父类构造方法
  6. public function __construct($name,$age,$job,$shengao){
  7. parent::__construct($name,$age,$job);
  8. $this->Shenggao = $shengao;
  9. self::$Count += 1;
  10. }
  11. // 重写父类show方法,同时调用父类的show方法
  12. public function show(){
  13. parent::show();
  14. echo '这是子类重写父类show方法';
  15. }
  16. public function staticCount(){
  17. echo '这是静态Person类的静态属性值:'.self::$Count;
  18. }
  19. }

Client

  1. <?php
  2. require 'autoLoad.php';
  3. $liu = new Man("刘德华",59,"歌手演员",180);
  4. $zhang = new Man("张学友",56,"歌手演员",182);
  5. $liu->show();//父类的show方法
  6. echo '<pre>';
  7. var_dump($liu);
  8. var_dump($zhang);
  9. // 通过对方访问方法,访问父类私有属性
  10. $liu->setAge(60);
  11. echo '通过对方访问方法,访问父类私有属性:'.$liu->getAge();
  12. echo '<br />';
  13. echo $liu->staticCount();
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!