深入理解面向对象8
2018年8月21日用parent代表父类 self代表自己,静态方法中调用方法在低版本中可以self::hee(),在高版本php中会报错 Deprecated: Non-static method family::caonima() should not be called statically in D:\wamp64\www\test\index.php 但是还是有结果输出的,推荐使用(new family())->caonima()这样调用 自己调用父类也是一样的.由此我们可以看出来静态的方法最好调用静态的属性和方法,其实个人感觉php类当中的方法在加载的过程中已经被静态化了,底层代码多用组合,顶层业务层多用继承.
1 2 3 4 5 6 7 8 9 10 11 12 |
自己调用自己的资源 自己调用父类资源 方法中调用方法 $this->heh() $this->nima(); | person::nima(); 方法中调用静态方法 self::heh() $this->say(); | person::say(); 静态方法中调用静态方法 self::heh() person::say(); 静态方法中调用方法 (new family())->caonima(); (new fulei())->caonima() 方法中调用属性 $this->name $this->name 方法中调用静态属性 self::$aa; person::$money 静态方法中调用静态属性 self::$aa; person::$money 静态方法中调用属性 (new family())->iiii; (new fulei())->iiii; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
<?php class person { public $name = 'zhangfang'; public $gender; static $money = 1000; public function __construct() { echo '这里是父类'.PHP_EOL; } public function say() { echo $this->name.PHP_EOL; } } class family extends person { static $hehe = 'hehhehe'; public function __construct() { person::__construct(); #调用父类的构造方法 echo '这里是子类'.PHP_EOL; } public function say() { person::say(); #调用父类的方法 } public function cry() { echo $this->name.PHP_EOL; echo parent::$money.PHP_EOL; #输出父类的属性 echo self::$money.PHP_EOL; #输出子类的属性 echo self::$hehe.PHP_EOL; } } $poor = new family(); $poor->name = 'Lee'; $poor->gender = 'female'; $poor->age = 25; $poor->say(); $poor->cry(); |