簡體   English   中英

當分配給 PHP 中的變量時,定義 class 的值

[英]Define value of class when assigned to variable in PHP

在 PHP 中,我可以使用 \ArrayAccess 創建一個 object 以便它可以分配為變量(數組),但在執行此操作時還可以執行一些其他操作,是否可以對單個值變量執行相同操作?例如:

$a = new MyClass(5, "some other stuff")->print(); //Prints 'some other stuff'
$b = $a * 2;
echo $b; //Prints 10

這個想法是在分配變量時返回第一個參數,但同時我可以用第二個參數做其他事情,到目前為止我只能使用 __invoke 魔術方法來做到這一點,但最終結果是像這樣的東西:

$a = new MyClass(5, "some other stuff")->print(); //Prints 'some other stuff'
$b = $a() * 2;
echo $b; //Prints 10

沒有 __invoke 方法可以做到嗎?

這是我設法用 \ArrayAccess 做到的方式(以防萬一它有幫助)

class MySQLK_customArray implements \ArrayAccess{

    private $storage = array();
    private $queryk;

    public function __construct($fetch_array, $query){
        $this->queryk = $query;
        $this->storage = $fetch_array;
    }

    public function offsetSet($key, $value)
    {
        if (is_null($key)) {
            $this->storage[] = $value;
        } else {
            $this->storage[$key] = $value;
        }
    }

    public function offsetExists($key)
    {
        return isset($this->storage[$key]);
    }

    public function offsetUnset($key)
    {
        unset($this->storage[$key]);
    }

    public function offsetGet($key)
    {
        if (! isset($this->storage[$key])) {
            return null;
        }
        $val = $this->storage[$key];
        if (is_callable($val)) {
            return $val($this);
        }
        return $val;
    }

    public function print(){
        echo $this->queryk.";";
        return $this;
    }

    public function get(){
        return $this->storage;
    }
}

可以這樣使用:

$arr = new MySQLK_customArray(array("id" => 1),"SELECT * FROM Table LIMIT 1")->print(); //Prints 'SELECT * FROM Table LIMIT 1'
echo $arr['id']; //Prints 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM