首页 > 解决方案 > 在PHP中分配给变量时定义类的值

问题描述

在 PHP 中,我可以使用 \ArrayAccess 创建一个对象,以便将其分配为变量(数组),但在执行此操作时还可以执行一些其他操作,是否可以对单个值变量执行相同操作?例如:

$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 方法可以做到吗?

标签: phpmagic-methods

解决方案


这是我设法用 \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

推荐阅读