Recently I found out about with and let statements for javascript.
I’m interested in achieving something like mentioned here: https://stackoverflow.com/a/1462102/393406, except for PHP in OOP fashion.
Like:
$builder = new markupbuilder();
with($markupbuilder){
div(
h1('A title...') .
p('This is ' . span('paragraph') . ' here.')
);
}
// respectively
$builder->div(
$builder->h1('A title...') .
$builder->p('This is' . $builder->span('paragraph') . ' here')
);
So, is there something similar for PHP or how could I achieve this in PHP?
This is sort of a trite reply, but you have not saved a single character of typing in your example, and I believe that’s the whole point of using
with. Thewithstatement also introduces ambiguity. Do you want to callgetElementsByTagNameon theDOMDocumentobject, or do you want to call the globally defined function of the same name?As for
let, PHP variables apply to the scope they are in by default — you have to use theglobalkeyword not only to make them globally accessible in general but any time you want to use them in another scope (and I would suggest never to use them period). Some may say it is a limitation on PHP thatifand other constructs don’t have their own scope, andletmay be useful there, but if you wanted another variable in one of those constructs you could just declare it separately or move the functionality to a function scope.