PHP magic: use it right, or don’t use it at all

Consider the following code snippet:

Explanation

Although we have text in the output, PHP tells us the variable is empty.

What’s wrong?

When using magic in PHP, you must be aware of all of its pro’s and con’s and what is going on behind.

‘$this->bar’ is a magic variable in the example. isset or empty are language constructs, which behave differently.

To correct the example, alter the code like this:

Conclusion

When using magic methods, make sure to implement all the methods you might need, and be careful with language constructs like isset, empty, include, require, …

Leave a Reply

Your email address will not be published. Required fields are marked *