0

I would like to use the list() statement in combination with an object.

$tuple = new Tuple();
// ..
list ($guestbook, $entry, $author) = $tuple;

This would work if $tuple was an array with three elements. But its an object.

Is there any way without using a method of Tuple (returning that kind of array) like implementing a fancy native interface I yet don't know?

MonkeyMonkey
  • 826
  • 1
  • 6
  • 19
  • maybe if the object implemented an Iterator, but never tried list() with that, so no idea. – Marc B Jul 13 '16 at 16:05
  • You need to get in the habit of [accepting answers](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) which help you to solve your issues. You'll earn points and others will be encouraged to help you. – Jay Blanchard Jul 13 '16 at 16:33
  • @JayBlanchard I will accept answers when I feel they are right. The given solutions are not very elegant, they "just" solve the technical problem which wasn't my question (I know how to convert an object into an array) - I am more curious about ideas behind this (casting objects, less dependencies) – MonkeyMonkey Jul 13 '16 at 18:35

3 Answers3

1

See this previous post: Convert PHP object to associative array

I am assuming (I haven't tested it) you could then do:

$tuple = new Tuple(); list ($guestbook, $entry, $author) = (array) $tuple;

Community
  • 1
  • 1
1

You can implement the interface ArrayAccess to do so:

class Tuple implements ArrayAccess {
  private $arr;

  public function __construct($arr) {
    $this->arr = $arr;
  }

  public function offsetExists($offset) {
    return array_key_exists($offset, $this->arr);
  }

  public function offsetGet($offset) {
    return $this->arr[$offset];
  }

  public function offsetSet($offset, $value) {
    return $this->arr[$offset] = $value;
  }

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

$tuple = new Tuple([1, 2, 3]);

list($am, $stram, $gram) = $tuple;

echo $am;
echo $stram;
echo $gram;

// outputs: 123
Iso
  • 3,148
  • 23
  • 31
  • Im a lazy programmer, so implementing four methods is not what I want - even though its a solution based on what I asked (but not really meant) – MonkeyMonkey Jul 13 '16 at 18:27
-1

You can do this:

$tumple = new Tumple();
$properties = get_object_vars($tumple);// ["guestbook" => "Feel", "entry" => "Good", "author" => "Inc"];
Alfredo EM
  • 2,029
  • 1
  • 14
  • 16