Laravel 如何像使用数组一样使用应用程序对象?

How does Laravel use the app object like its an array?

我正在 PHP 中设置一个应用程序,试图遵循 Laravel 中规定的一些约定,我可以看到有很多对 $this->app["some_var"];[= 的引用16=]

但是在我的应用程序中它抛出一个错误说 "Cannot use object as an array"。

我知道 Laravel 使用了魔术方法,例如 __get()__set() 我已经包含了,但是我仍然得到相同的结果。

我在 App 对象的父级 class 中使用的魔法 getter 和 setter 代码

  /**
  * Dynamically access container services.
  *
  * @param  string  $key
  * @return mixed
  */
  public function __get($key)
  {
    return $this[$key];
  }

  /**
   * Dynamically set container services.
   *
   * @param  string  $key
   * @param  mixed   $value
   * @return void
   */
  public function __set($key, $value)
  {
    $this[$key] = $value;
  }

预期结果是访问对象上任何属性不可访问的对象?

当前抛出一个 Fatal error: Uncaught Error: Cannot use object Application as type of array.

您需要实现 ArrayAccess 请参阅 https://www.php.net/manual/en/class.arrayaccess.php 中的以下代码 以下代码将数组值存储在 $container 数组中,并将 $obj['key'] 代理到此数组对象

<?php
class obj implements ArrayAccess {
    private $container = array();

    public function __construct() {
        $this->container = array(
            "one"   => 1,
            "two"   => 2,
            "three" => 3,
        );
    }

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

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

    public function offsetUnset($offset) {
        unset($this->container[$offset]);
    }

    public function offsetGet($offset) {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }
}

$obj = new obj;

var_dump(isset($obj["two"]));
var_dump($obj["two"]);
unset($obj["two"]);
var_dump(isset($obj["two"]));
$obj["two"] = "A value";
var_dump($obj["two"]);
$obj[] = 'Append 1';
$obj[] = 'Append 2';
$obj[] = 'Append 3';
print_r($obj);
?>

数组和对象在PHP中是两种不同的数据类型。为了访问数组变量,我们需要使用方括号 [ ]。 例如,

$a = array('one','two','three');
$a[] = "four";
echo $a[3]; //Output: four.

但是,对于访问对象变量

$a = new {className}();
$a->key = 'value'; //Using magic method __get()
echo $a->key; //Output: value

在class方面,$this指的是特定class的对象。因此,您不能使用 [ ] 方括号分配变量。为此,您需要使用 -> 箭头。

在 class 中,您需要按如下方式重写您的函数

public function __get($key) {
 return $this->$key ?: false;
}

public function __set($key,$value) {
 $this->$key = $value;
}

否则,您可以在 class 中创建一个新的数组变量,如下所示

class className {
 public $a = array();
 public function __get($key) {
   return $this->a[$key] ?: false;
 }
 public function __set($key,$value) {
   return $this->a[$key] = $value;
 }
}

来自 Laravel 内核的 class 应用程序扩展了一个实现 ArrayAccess 的容器 class。

有多种方法可以构建 ArrayAccess 接口,Laravel 使用了一种复杂的方法,因为它应该比默认方法满足更多的要求,但简而言之,您需要为 offsetExists( )、offsetGet()、offsetSet() 和 offsetUnset() 方法,然后您可以使用 ArrayAccess 语法。

您可以在您的容器 class 中看到 ArrayAccess 的扩展用法,默认情况下在供应商上,遵循下一个路径:Illuminate\Container\Container 并且有实现这些方法的代码:

/**
 * Determine if a given offset exists.
 *
 * @param  string  $key
 * @return bool
 */
public function offsetExists($key)
{
    return isset($this->bindings[$key]);
}

/**
 * Get the value at a given offset.
 *
 * @param  string  $key
 * @return mixed
 */
public function offsetGet($key)
{
    return $this->make($key);
}

/**
 * Set the value at a given offset.
 *
 * @param  string  $key
 * @param  mixed   $value
 * @return void
 */
public function offsetSet($key, $value)
{
    // If the value is not a Closure, we will make it one. This simply gives
    // more "drop-in" replacement functionality for the Pimple which this
    // container's simplest functions are base modeled and built after.
    if (! $value instanceof Closure) {
        $value = function () use ($value) {
            return $value;
        };
    }

    $this->bind($key, $value);
}

/**
 * Unset the value at a given offset.
 *
 * @param  string  $key
 * @return void
 */
public function offsetUnset($key)
{
    unset($this->bindings[$key], $this->instances[$key], $this->resolved[$key]);
}

了解 ArrayAccess 的最简单方法就像 Somesh Mukherjee 的回答解释。