
Oded Arbel - 2017-04-12 15:07:11
I think your basic premise is wrong - in your templating engine, instead of prepopulating any and all possible values on the object, you can just check if the property is set on the object using isset() before accessing it, and if not, just display that default value (the empty string probably). Writing a new base class for this feature is kind of an overkill.
That being said, all the issues you have with stdClass seem either superficial or to stem from a misunderstanding of how property access is done in PHP.
For example, to execute lambdas assigned as closures to object properties, you need to first resolve the property to its value (the lambda) and only then execute it (using parenthesis), but because the parenthesis "operation" binds closer than anything else (otherwise almost everything else will break) when you say "$o->m()", PHP first tries to resolve "m()" and understands it as "method call for method m" and only then applies that using the "->" operator to object "$o" and that fails because "m" is a field and not a method (in PHP, like in most languages that are not JavaScript, there's a difference).
Instead, the correct way of calling lambdas stored as object properties, is to use parenthesis to force the binding order that you want, like this:
($o->m)();
And that works well. You can even have the field name resolution be dynamic, like so:
$f = "m";
($o->$f)();
The other important feature you present, which is an updated $this reference for assigned lambdas, is implemented in PHP using Closure::bindTo(), which I don't see much of a problem using it explicitly when you need it - and it's even friendly to JavaScript immigrants, as it resembles quite well the Function.bind() syntax from JavaScript.
Summary: dynClass is basically a syntactic sugar coating for stdClass, and if you like artificial sweeteners in your code then that's perfectly fine - I'm personally am wary of the loss if readability that this incurs and would prefer to keep my property access looking more like PHP and less like magic. Though I think it speaks to how awesome PHP is, that you can do something like this.