Let’s say that PHP isn’t the best, if it goes with language organisation. But thing I discovered yesterday scared me and surprised in the same moment. I know about ability to nest function in function (I even saw something implemented this way…), but didn’t know that we can call nested method like in the listing bellow. Please, don’t do this ever!

Let’s say that PHP isn’t the best, if it goes with language organisation. But thing I discovered yesterday scared me and surprised in the same moment. I know about ability to nest function in function (I even saw something implemented this way…), but didn’t know that we can call nested method like in the listing bellow. Please, don’t do this ever!

EDIT (12-11-2010)
Let’s exmplain how it works. If you call myPublicMethod on the object of myClass it puts the definition of uglyFunction to the global scope so it’s accessible to everyone (it is kind of dynamic function declaration). Since myPublicMethod doesn’t returns anything, the concatenation with uglyFunction will remain uglyFunction call unchanged, but the function will be accessible in global scope, because everything evaluates during concatenation. Note that if you call again myPublicMethod the fatal error will be raised: Fatal error: Cannot redeclare uglyfunction()

Anyway, don’t do this at home!

EDIT (12-11-2010)
Let’s exmplain how it works. If you call myPublicMethod on the object of myClass it puts the definition of uglyFunction to the global scope so it’s accessible to everyone (it is kind of dynamic function declaration). Since myPublicMethod doesn’t returns anything, the concatenation with uglyFunction will remain uglyFunction call unchanged, but the function will be accessible in global scope, because everything evaluates during concatenation. Note that if you call again myPublicMethod the fatal error will be raised: Fatal error: Cannot redeclare uglyfunction()

Similar posts

It’s nothing new – this is mentioned in the manual. The only weird thing I see here is the concatenation ‘.’ operator between the calls. But it could be safely exchanged with a semicolon (;). Then everything looks normal ;)

http://blog.kowalczyk.cc Tomasz Kowalczyk

You can use a little bit more weird construction – enclose uglyFunction with a conditional if(function_exists()) and you’ll have dynamic function factory. ;]

Autor

Wojciech Sznapka:
Programming passionate, focused on web technologies with more than 9 years in the industry. On daily basis he designs systems, chooses solutions and implements them. His main areas of interest are software architecture, big data, data mining and Internet of Things.
Google +