php - 在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 方法可以做到吗?
解决方案
这是我设法用 \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
推荐阅读
- javascript - Typescript 生成 typescript 而不是 javascript
- acumos - 将 .tf 和可能的 .txt 文件依赖项上传到 Acumos
- java - 在 JAVA 中按特定单词拆分字符串
- javascript - 取消选择复选框并使用 jQuery 选择当前复选框
- kubernetes - Kubernetes 节点的时间同步问题
- php - 给初学者的 REST API 建议
- twilio - 通过 REST API 的 Twilio 挂断电话不起作用?
- excel - 将可编辑行添加到受保护的 Excel 电子表格
- javascript - 使用 lodash orderBy 或 sortBy 并处理空值
- swift - 格式化条形图 x 轴值、条形和标签