7

PHP 字符串中直接解析函数的写法

 2 years ago
source link: https://segmentfault.com/a/1190000040687221
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP 字符串中直接解析函数的写法

PHP 中的字符串理论上是不能够解析函数的,仅能够解析变量。最近发现一种特殊的写法,是可以让字符串直接解析函数的。

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

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

个人认为这种写法实际上还是通过解析变量实现的。= 左边是一个特殊名称的变量,= 右边只要符合赋值变量的代码块均可以在字符串中解析。

以下代码仅供学习交流,实际工作中不建议用这种写法。

$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."
var_dump("fruits: ${!${''} = $fruit ?? 'apple'}.");
// string(14) "fruits: apple."

var_dump("fruits: ${!${''} = isset($fruit) ? $fruit : 'apple'}.");
// string(14) "fruits: apple."
$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."
class Fruit
{
    public function __toString()
    {
        return 'banana';
    }

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

https://www.guanguans.cn


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK