1. 程式人生 > 實用技巧 >PHP面向物件程式設計(三)

PHP面向物件程式設計(三)

PHP靜態屬性和靜態方法

靜態屬性和方法的定義與呼叫

通過static關鍵字來修飾靜態屬性和方法。由於靜態屬性和方法可以直接通過類引用,所以又被稱為類屬性和方法(相應的非靜態屬性和非靜態方法需要例項化後通過物件引用,因此被稱為物件屬性和物件方法),靜態屬性和方法通過 類名::屬性/方法的方式呼叫。

<?php
class Car
{
	public static $wheels = 4;
	
	public static function getWheels()
	{
		return self::$wheels;
	}
}

//呼叫
Car::getWheels();
Car::$wheels;

靜態屬性和方法同樣支援設定private、protected、public三種可見性級別。

靜態屬性動態修改

Car::$wheels = 8;

呼叫另一個類的靜態屬性方法

通過類名::屬性/方法呼叫。

靜態方法的繼承和重寫

<?php
class Car
{
	public static $wheels = 4;
	
	public static function getWheels()
	{
		return self::$wheels;
	}
	
	 public static function getClassName()
    {
        return __CLASS__;
    }

    public static function who()
    {
        echo self::getClassName() . PHP_EOL;
    }
}

class LynkCo01 extends Car
{
    public static function getClassName()
    {
        return __CLASS__;
    }
}

_CLASS_ 可以獲取當前的類名

self 指向的是定義時持有他的類

靜態繫結

class Car
{
    ...

    public static function getClassName()
    {
        return __CLASS__;
    }

    public static function who()
    {
        echo static::getClassName() . PHP_EOL;
    }
}

class LynkCo01 extends Car
{
    public static function getClassName()
    {
        return __CLASS__;
    }
}

...

Car::who();
LynkCo01::who();

結果

Car
LynkCo01

static指向的是呼叫它的方法所在的類,而不是定義時

PHP 魔術方法、序列化與物件複製

__sleep()、__wakeup() 與物件序列化

<?php

class Car
{
    protected $brand;

    public static $WHEELS = 4;

    /**
     * @return mixed
     */
    public function getBrand()
    {
        return $this->brand;
    }

    /**
     * @param mixed $brand
     */
    public function setBrand($brand): void
    {
        $this->brand = $brand;
    }
}

$car = new Car();
$car->setBrand("領克01");

// 將物件序列化為字串後儲存到檔案
$string = serialize($car);
file_put_contents("car", $string);

物件序列化字串內容

O:3:"Car":1:{s:8:"*brand";s:8:"領克01";}

在通過unserialize將物件字元反序列化為物件。

// 從檔案讀取物件字串反序列化為物件
$content = file_get_contents("car");
$object = unserialize($content);
echo "汽車品牌:" . $object->getBrand() . PHP_EOL;

_ __sleep() 如果在類中存在的話,會在序列化方法 serialize 執行之前呼叫,以便在序列化之前對物件進行清理工作,相對的, __wakeup() 如果在類中存在的話,會在反序列化方法 unserialize 執行之前呼叫,以便準備必要的物件資源。

__call() 和 __callStatic()

在物件上呼叫一個不存在的成員方法時,觸發__call。

指定類上呼叫一個不存在的靜態方法觸發__callStatic.

__set()、__get()、__isset() 和 __unset()

__set() 方法會在給不可訪問屬性賦值時呼叫; __get() 方法會在讀取不可訪問屬性值時呼叫;當對不可訪問屬性呼叫 isset() 或 empty() 時, __isset() 會被呼叫;當對不可訪問屬性呼叫 unset() 時,__unset() 會被呼叫。

__invoke()

在以函式方式呼叫物件時執行。

__clone()與物件複製

當我們以 clone 關鍵字執行物件複製時,會呼叫這個方法,我們可以通過該方法操縱物件複製的最終結果。