3

The writing of the direct parsing function in the PHP string

example

In theory, strings in PHP cannot parse functions, but can only parse variables. I recently discovered a special way of writing that allows strings to parse functions directly.

Writing

// 单行
${!${''} = 代码}

// 多行
${!${''} =
    代码
}

I personally think that this way of writing is actually achieved by parsing variables. = left of 0614168cbe8513 is a variable with a special name, and = , any code block that matches the assigned variable can be parsed in the string.

Example

The following code is only for learning and communication, and this method of writing is not recommended in actual work.

one,

$fruits = implode('、', ['apple', 'banana']);
var_dump("fruits: $fruits."); // 正常写法解析变量
// string(23) "fruits: apple、banana."

var_dump("fruits: implode('、', ['apple', 'banana'])."); // 错误写法不能够解析函数
// string(44) "fruits: implode('、', ['apple', 'banana'])."

var_dump("fruits: ${!${''} = implode('、', ['apple', 'banana'])}."); // 特殊写法解析函数成功
// string(23) "fruits: apple、banana."

var_dump("fruits: ${!${''} = implode('、',
    [
        'apple',
        'banana'
    ])}."
); // 多行书写依然解析函数成功
// string(23) "fruits: apple、banana."

two,

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

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

three,

$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."

Four,

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

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

Original link

https://www.guanguans.cn


guanguans
2.4k 声望89 粉丝

No practice, no gain in one's wit.