- <?PHP
- /* 关于php面向对象动态绑定和静态绑定的理解 */
- // 1,理解public protected private 访问级别
- // eg:视图继承父类private级别的属性和方法
- class User
- {
- private $name = "wxp";
- private function setName($name)
- {
- if(isset($this->name))
- {
- $this->name = $name;
- }
- }
- }
- class sUser extends User
- {
- }
- $sUser = new sUser();
- // print_r($sUser->name); // 输出:未能访问到父类private属性
- // 2,动态绑定
- // 继承时会发生动态绑定,即:子类复写父类的方法或成员,当该方法或成员被调用时,会判断调用其的实例,是属于哪个类的实例就调用谁的。
- // 注意该成员或方法的访问级别若是private则会发生静态绑定
- class Users
- {
- protected function isPassed()
- {
- return false;
- }
- public function delUsers()
- {
- if(!$this->isPassed())
- {
- print('error');
- return false;
- }
- else
- {
- print("ok");
- }
- }
- }
- class PassUsers extends Users
- {
- protected function isPassed()
- {
- return true;
- }
- }
- $users = new Users();
- $passusers = new PassUsers();
- // $users->delUsers(); //echo :error
- // $passusers->delUsers(); //echo : ok
- // 3 模拟静态绑定
- // private 级别的成员或方法只属于当前类,父类,所以即使子类重写,他几经在父类编译时期静态绑定,不会调用子类重写的isPassed方法。
- class Users_
- {
- private function isPassed()
- {
- return false;
- }
- public function delUsers()
- {
- if(!$this->isPassed())
- {
- print('error');
- return false;
- }
- else
- {
- print("ok");
- }
- }
- }
- class PassUsers_ extends Users_
- {
- private function isPassed()
- {
- return true;
- }
- }
- $users_ = new Users_();
- $passusers_ = new PassUsers_();
- $users_->delUsers(); //echo :error
- $passusers_->delUsers(); //echo : error