-1

Is it possible to create a PHP class that can hold whatever type of data you throw at it, even recursively, using magic methods?

I saw this: PHP - Indirect modification of overloaded property

but it doesn't handle recursive data:

class ActiveRecord extends Creator {

}

$a = new ActiveRecord();

$a->_id = "123456789";
$a->persona_info = [
    "name" => "Bob",
    "surnames" => ["First", "Second", "Third"]
];
$a->history = [
    "logins" => [
        [
            "date" => "1999",
            "ip" => "1.2.3.4"
        ],
        [
            "date" => "1129",
            "ip" => "1.2.3.4"
        ]
    ],
    "purchases" => [
        [
            "date" => "1819",
            "amount" => "1884"
        ],
        [
            "date" => "1459",
            "amount" => "14"
        ]
    ]
];

var_dump($a->history->logins);

That gives me:

PHP Notice:  Trying to get property of non-object in /tmp/x.php on line 90
PHP Stack trace:
PHP   1. {main}() /tmp/x.php:0
NULL

Trying to investigate further, I see that $a->history is a plain php array instead of a Value object (or even a Creator object.

Community
  • 1
  • 1
alexandernst
  • 14,352
  • 22
  • 97
  • 197
  • You should post the `Creator` class as well – DarkBee Apr 06 '15 at 17:46
  • @DarkBee It's in the link in my question. – alexandernst Apr 06 '15 at 17:46
  • Dont think most people tend to click through. I did not at first read, anyway you are using the modified version of the `creator` class? – DarkBee Apr 06 '15 at 17:48
  • You need to return another object that also has magic methods, not the raw array. – Barmar Apr 06 '15 at 17:53
  • @Barmar Where should that be? In the `__get` method of `Value`? – alexandernst Apr 06 '15 at 17:56
  • Possibly, I'm not exactly sure. – Barmar Apr 06 '15 at 17:58
  • At first glance i'm not sure you can convert the `login` key to a `StdClass`, because how would you retrieve the values in it? A property name can't start with a numeric value. You will need to alter the `__get` method and create a class that is able to retrieve these value for instance with the interface `ArrayAccess` – DarkBee Apr 06 '15 at 18:07

1 Answers1

-1

The problem is $a->history is an array and not a object. It should be var_dump($a->history['logins']);

SameOldNick
  • 2,397
  • 24
  • 33
  • Yes, that would work for this specific case, but my question is more broad. I'm trying to access values using `->`, which means that each value should be an object, which then should contain all children values, etc. – alexandernst Apr 06 '15 at 17:49
  • That's the problem. If you want it to be a object then you need to declare it differently and not like that. – SameOldNick Apr 06 '15 at 17:50
  • OP is using magic methods to modify passed data, in this case convert array to `StdClass`, see linked answer – DarkBee Apr 06 '15 at 17:51