Features of PHP OOP - Encapsulation

1. What is encapsulation?

Hide object fields and implementation details, control the read and access levels of fields in the program only through external interfaces, and
combine abstract behavior and data to form an organic whole.

2, the scope of the field

<?php
classs Conputer{
//public  公共的,内外可以访问
//private 私有的,类内可以访问
//protected  受保护的,类内和子类可以访问
//类内指的是{}之间的部分
}
?>

3. instanceof keyword

Determines whether an object is an instance of a class, an instance of a subclass of a class, or implements an interface

4. Interceptor

It can be made private, or static methods can be set, just like ordinary field settings.

5. Constant;

<?php
class Computer{
const PI=3.14;
}
?>

6. Static fields and methods

1. Summary: Static methods can only access static, or constants, using the self keyword;

<?php
//类名一般第一个字母大小
class Computer{

    const PI=3.1415926;//常量,在该类所有的实例化对象的生命周期内,值不变,约定俗成 常量名称大写

    public static $_count=0;  //静态类字段

    private $_name='联想'; //我是公共字段,内外可以访问,初始化不可以赋值变量,如 $_name=time();错误

    private $_cpu; //我是私有字段,类内可以访问

    protected $_zb; //我是受保护的字段,子类和类内可以访问

    public function _run(){
        //类内访问字段:  $this->字段名称
       $this->_cpu='I5';
    }

    //静态方法可以通过类—>方法名称访问,也可以通过 类名称::方法名称访问
    //静态方法,不可以访问非静态字段,非静态方法,通过$this也无法访问,因为不在对象中
    //静态方法,可以访问静态字段,静态方法,
    //静态方法内部,不可使用$this关键字
    //静态只能访问静态 ,或者常量,
    public static function _run2(){
       echo self::$_count;
       //self::_run(); 错误
       //self::_name; 错误
       self::PI;
    }

    //普通方法可以访问静态方法,因为,静态方法是为了对所有实例共享的
    public function _run3(){
        self::_run2();
    }

    //拦截器
    //变量有用
    private function __set($varname,$varvalue){
        $this->$varname=$varvalue;
    }

    private function __get($varname){
        return $this->$varname;
    }
}

//实例化一个类
$computer=new Computer();
$computer1=new Computer();
Computer::_run2();
echo '<br>';
$computer->_run2();
echo '<br>';
//访问常量
echo Computer::PI;
echo '<br>';
//echo Computer::$_count;
//echo $computer->_count;  无法访问
//echo $computer->PI;   无法访问

//拦截器 设置变量值
$computer->_name="dell";
echo '<br>';
echo $computer->_name;
echo '<br>';
$computer->_count="dell";
echo '<br>';
echo $computer->_count;
echo '<br>';
echo Computer::$_count;

//instanceof 关键字 确定某个对象是否是一个类的实例。一个类的子类,或者是实现了某个接口,

echo ($computer instanceof Computer);
?>

Features of PHP OOP - Encapsulation

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324843052&siteId=291194637