0

I have the following issue:

The current code of an application I'm working on contains a very large number of definitions like this:

$obj = new stdClass();
$obj->a->b = "something";

This results in: PHP Strict Standards: Creating default object from empty value in [somewhere].

The correct form would be:

$obj = new stdClass();
$obj->a = new stdClass();
$obj->a->b = "something";

Now the problem: Replacing this throughout the code would take ages (consider thousands of cases, with conditions, etc.).

So I was thinking of replacing stdClass with a custom object (this would be a simple replace in code), creating a setter for it that verifies if the variable property is an object, and defines it as object if it is before setting the second property.

So we get:

class MockObject() {
    public function __set($property, $value) {
        // Do stuff here
    }
}

$obj = new MockObject();
$object->a->b = "something";

The problem is that when executing $object->a->b = "something"; setter is not called (because you don't actually set the a property, but the b property).

Is there any way around this? Or is other solution possible?

Note: Explicitly calling the __set() method is not a solution since it would be the same as defining properties as stdClass().

2 Answers 2

3

You know about the magic setter. Use a magic getter also.

If it wants to get a var that does not exists: create one (in an array or something like that) that is an instance of that class.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah... you are right. Ty. Seems I'm very tired that did not think of that. +1.
Even after your update, my answer remains the same. If you want to set something to a subclass that is not set (and pretends to be a StdClass), just make use of a magic getter. And for the setting you can use the magic Setter. Set the vars into an array with the right key, and that should fix your described problem.
0

Why don't you initialize your b variable in the constructor of the A class ?

 public function __construct()
 {
   $this->b = new B();
 }

1 Comment

Because I don't know what b is (it is dynamic). b can be contactDetails, orders, services, anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.