0

I've built a singleton class with chaining methods (to be used in a template).

To make chaining work I need to return new static. It allows the next chain to be added. The problem I have is that I don't want to return the static object if there are no more chains.

Example

<?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

In the example above I want $blueprints to return an array, because there are no more methods chained on it.

How can that be done?

Jens Törnell
  • 23,180
  • 45
  • 124
  • 206
  • 2
    A method cannot know how its output will be used. How about `$a = B::c(); $a->d()`? There's no sane way to detect that. You're also badly mixing up static and non-static calls. Not a sane approach at all. – deceze Mar 29 '17 at 08:49
  • @deceze By experience I know you are always right. I thought about doing something like this `bread::blueprint('projects', 'en')->fields('title')->value('label');` to have it as a one-liner, but I probably need to go with an argument array instead. Thanks! – Jens Törnell Mar 29 '17 at 08:55

2 Answers2

2

The simple answer is you cannot do what you want. Method chaining is not a special thing for Php. For your example

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

This is not different than:

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

So because of the Php does not know the context where the result will be used of it cannot change the return type. Here is another version of this question: Check if call is method chaining

However, your class can implement ArrayAccess interface.This will allow you to treat the object like an array without casting and you get total control over how the members are used.

Community
  • 1
  • 1
Serdar Saygılı
  • 461
  • 3
  • 13
-1

You can try this: $blueprints = (array)bread::blueprints();