Can you please tell me what kind of PHP syntax is:
echo Html::{'div.my-class#my-id'}('This is element content')
?
It’s from https://github.com/decodelabs/tagged library.
I mean I know what it does, but I don’t understand the syntax used and why it works 🙂 (braces immediately after the scope operator). Looks like they’re using braces to ‘generate’ the name of the function to call, but – on the other hand – it contains characters like ‘.’ and ‘#" and variable parameters (‘my-class’, ‘my-id’). I’m confused…
I tried googling for over 2 hours, but no luck :/
3
Answers
The following code does not answer the question, but shows a working example:
OUTPUT
I tested this code with PHP 8.2. Once the
convert()
function has the name and text, it should then be fairly straightforward to parse the details and (for example) add an HTML element to the DOM or manipulate an existing element.let’s reconstruct this from first principle
{value}
to put a dynamic method/attribute namei.e if you have
you can do
as you can do this and
'walk'
and name are value, they can also come from variablesfor example
__callStatic()
will be called whenever you call a static method for which the name is undefinedlike this
will output
Calling object method 'iDontExist'
It will output
Calling object method 'Hello World'
Conclusion
{}
syntax you can have method that don’t follow normal convention (i.e they can have spaces, emoji, special caracters etc. )__callStatic
you can have methods that don’t exists before handso by combining 1 and 2 your library is allowing a method to already be an argument by itself and all the logic of treating this name will be in a
__callSatic
so it would be the same as doing
Html::something('div.my-class#my-id', 'This is element content' )
if something was a defined static methodI think there’s a class named
HTML
which is calling a static method dynamically to output some HTML.In the example below, I’m dynamically calling a method which, in a simple way, does the same thing. I’m also passing an argument to generate additional text.