PHP面向对象

67 阅读1分钟

面向对象

php使用class定义对象

创建类

class A{
    var $var1 = "1";
    function A_echo(){
        echo $this->var1; // 类中访问自身变量不需要使用$符
    }
}

$this代表类的实例本身


实例化

$a = new A;

如果含有构造函数,需要传参数

$a = new A($a, $b);

属性

class Website
{
    public $name = 'this is a class var';

    public function demo()
    {
        echo 'this is a class function ';
    }
}
$a = new Website(); // 实例化
$a->name = 'this is new'; // 实例变量赋值
$a->demo(); // 实例方法调用
$a->name; // 实例变量获取 

构造函数

php使用__construct方法在类中定义构造方法

class Website{
    public $name, $url, $title;
    public function __construct($str1, $str2, $str3){
        $this -> name  = $str1;
        $this -> url   = $str2;
        $this -> title = $str3;
        $this -> demo();
    }
    public function demo(){
        echo $this -> name.'<br>';
        echo $this -> url.'<br>';
        echo $this -> title.'<br>';
    }
}

析构函数

析构函数与构造函数不同,析构函数会在对象被销毁时自动调用,一般用来执行资源释放的工作

析构函数不能带有任何参数

public function __destruct(){
    echo '------这里是析构函数------<br>';
}

魔法方法

function nameDes
__set()在给未定义的属性赋值时自动调用
__get()调用未定义的属性时自动调用
__isset()使用 isset() 或 empty() 函数时自动调用
__unset()使用 unset() 时自动调用
__sleep()使用 serialize 序列化时自动调用
__wakeup()使用 unserialize 反序列化时自动调用
__call()调用一个不存在的方法时自动调用
__callStatic()调用一个不存在的静态方法时自动调用
__toString()把对象转换成字符串时自动调用
__invoke()当尝试把对象当方法调用时自动调用
__set_state()当使用 var_export() 函数时自动调用,接受一个数组参数
__clone()当使用 clone 复制一个对象时自动调用
__debugInfo()使用 var_dump() 打印对象信息时自动调用

self/this

$this是实例化对象的指针,self是对象的指针

$this->name;
self::name;

静态的方法中不能使用$this,静态方法给类访问的


class Website
{
    public $name = 'this is a class var';
    static $static_naem = 'this is static name';
    public function demo(){
        echo 'this is a class function ';
        echo self::$static_naem;
    }
}

$a = new Website();
$a->name = 'new this name';
Website::$static_naem = 'new static name';
echo Website::$static_naem;
echo $a->name;

类中常量

可以把在类中始终保持不变的值定义为常量,在定义和使用常量的时候不需要使用$符号

常量的值必须是一个定值,不能是变量,类属性,数学运算的结果或函数调用

class MyClass
{
    const constant = '常量值';
    function showConstant() {
        echo  self::constant . PHP_EOL;
    }
}

echo MyClass::constant . PHP_EOL;

$classname = "MyClass";
echo $classname::constant . PHP_EOL; // 自 5.3.0 起

$class = new MyClass();
$class->showConstant();
echo $class::constant . PHP_EOL; // 自 PHP 5.3.0 起