How to let string parsing function directly in PHP? The following article will share with you how to write direct parsing functions in PHP strings. I hope it will be helpful to you!
String in PHP Theoretically, functions cannot be parsed, only variables can be parsed. Recently I discovered a special way of writing that allows string parsing functions to be directly parsed.
Writing
// 单行 ${!${''} = 代码} // 多行 ${!${''} = 代码 }
Personally, I think this writing method is actually achieved by parsing variables. =
The left side is a variable with a special name, =
The right side can be parsed in the string as long as the code block conforms to the assigned variable.
Example
The following code is only for learning and communication. This writing method is not recommended in actual work.
一、
$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."
4.
class Fruit { public function __toString() { return 'banana'; } } var_dump("fruits: ${!${''} = new Fruit() }."); // string(15) "fruits: banana."
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Let's talk about how to directly parse string functions in PHP (skill sharing). For more information, please follow other related articles on the PHP Chinese website!