PHP return array if breaking chain in singleton

PHP return array if breaking chain in singleton

我用链接方法构建了一个单例 class(将在模板中使用)。

要使链接正常工作,我需要 return new static。它允许添加下一个链。我遇到的问题是,如果没有更多的链,我不想 return 静态对象。

例子

<?php
class bread {
  public static $array;
  public static function blueprints() {
    static::$array = array('some', 'values');
    return new static;
  }
  public static function fields() {
    return static::$array;
  }
}

$blueprints = bread::blueprints();
$fields = bread::blueprints()->fields();

print_r($blueprint) // Returns object - FAIL
print_r($fields ) // Returns array - OK

在上面的示例中,我希望 $blueprints 到 return 一个数组,因为没有更多的方法链接在它上面。

如何做到?

你可以试试这个: $blueprints = (array)bread::blueprints();

简单的答案是你不能做你想做的事。 方法链接对于 Php 来说并不是什么特别的事情。 举个例子

bread::blueprints()->fields();

这与以下内容没有区别:

$tmp = bread::blueprints();
$tmp->fields();

因此,由于 Php 不知道将使用结果的上下文,因此无法更改 return 类型。 这是这个问题的另一个版本: Check if call is method chaining

但是,您的 class 可以实现 ArrayAccess interface.This 将允许您像对待数组一样处理对象而无需强制转换,并且您可以完全控制成员的使用方式。