Writing method of direct parsing function in PHP string

Time:2022-1-19

Writing method of direct parsing function in PHP string

Writing method of direct parsing function in PHP string

In theory, strings in PHP cannot parse functions, only variables. Recently, a special writing method has been found, which allows strings to directly parse functions.

Writing method

//Single line
${! ${''} = code}

//Multiline
${!${''} =
    code
}

Personally, I think this writing method is actually realized by analyzing variables.=On the left is a variable with a special name,=On the right, as long as the code blocks that match the assigned variables can be parsed in the string.

Example

The following code is only for learning and communication. This writing method is not recommended in practical work.

I

$fruits = implode('、', ['apple', 'banana']);
var_ dump("fruits: $fruits."); //  Normal writing analytic variable
// string(23) "fruits: apple、banana."

var_ dump("fruits: implode('、', ['apple', 'banana'])."); //  Incorrect writing cannot parse function
// string(44) "fruits: implode('、', ['apple', 'banana'])."

var_ dump("fruits: ${!${''} = implode('、', ['apple', 'banana'])}."); //  Special writing parsing function succeeded
// string(23) "fruits: apple、banana."

var_dump("fruits: ${!${''} = implode('、',
    [
        'apple',
        'banana'
    ])}."
); //  Multi line writing still resolves the function successfully
// string(23) "fruits: apple、banana."

II

var_dump("fruits: ${!${''} = $fruit ?? 'apple'}.");
// string(14) "fruits: apple."

var_dump("fruits: ${!${''} = isset($fruit) ? $fruit : 'apple'}.");
// string(14) "fruits: apple."

III

$fruit = function (){
    return 'banana';
};
var_dump("fruits: ${!${''} = $fruit() }.");
// string(15) "fruits: banana."

var_dump("fruits: ${!${''} = call_user_func(function (){
    $fruits = [
        'apple',
        'banana'
    ];
    
    return implode('、', $fruits);
}) }.");
// string(23) "fruits: apple、banana."

IV

class Fruit
{
    public function __toString()
    {
        return 'banana';
    }

}
var_dump("fruits: ${!${''} = new Fruit() }.");
// string(15) "fruits: banana."

Original link

https://www.guanguans.cn