PHP encapsulation & inheritance

PHP test packaging and inheritance features

Through encapsulation, some data and methods can be hidden to achieve the purpose of protection. Through inheritance, the amount of redundant code is reduced.

<?php
    class people {
    
    
        public $name;
        public $age;
        public $number;
        protected $salary;	//不能让外人轻易看到薪水是多少
        //构造方法
        function __construct ($name = '默认', $age = 1, $number = 111, $salary = 10000){
    
    
            $this->name = $name;
            $this->age = $age;
            $this->number = $number;
            $this->salary = $salary;
            echo '调用构造方法<br />';
        }
        public function run(){
    
    
            echo '我正在跑步!';
        }
        public function say() {
    
    
            echo '我叫'."$this->name".',我的年龄是'.$this->age.',我的电话是'.$this->number.'<br/>';
        }
    }
    class Man extends people{
    
    	//子类Man继承父类people
        protected $salary;  //子类新增成员属性

        public function getSalary($name){
    
    
            if($name == '亲人') {
    
    
                echo '薪水是'.$this->salary;
            } else {
    
    
                echo '我没有存款!<be />';
            }
        }
        public function run(){
    
      //子类重写父类方法
            echo '我已经飞了!';
        }
    }

    $P1 = new people('张三', 18, 123456);	//实例化一个对象,默认调用构造器
    $P1->say();
    $Man1 = new Man('李四',19,15070864137);
    $Man1->run();
    $Man1->getSalary('亲人');	//传入的参数如果不是亲人,则不会输出真正的薪水

?>

Guess you like

Origin blog.csdn.net/qq_53703628/article/details/115371332