Get the App
SLTechnology News&Howtos  ›  Development  › 

How to make string parse function directly in PHP

Shulou Source: shulou.com Published: 2022-06-03 07:20:29 10月05日 Update

This article is about how to make strings parse functions directly in PHP. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The Writing of Direct Analytic function in PHP string

Strings in PHP cannot theoretically parse functions, only variables. Recently, it has been found that a special way of writing allows strings to parse functions directly.

Writing method

/ / single line ${! ${'} = code} / multiple lines ${! ${'} = code}

Personally, I think this kind of writing is actually realized by parsing variables. On the left side is a variable with a special name, and on the right side any code block that matches the assigned variable can be parsed in a string.

Example

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

I.

$fruits = implode (',', ['apple',' banana']); var_dump ("fruits: $fruits."); / / parsing variables / / string (23) "fruits: apple, banana." var_dump ("fruits: implode (',', ['apple',' banana']).") / / function / / string (44) "fruits: implode (',', ['apple',' banana'])." var_dump ("fruits: ${! ${'} = implode (',', ['apple',' banana'])}.") / / string (23) "fruits: apple, banana." var_dump ("fruits: ${! ${'} = implode (',', ['apple',' banana'])}."); / / Multi-line writing is still successful / / 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."

3.

$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." Thank you for reading! This is the end of this article on "how to make string parsing function directly in PHP". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Tags: Function writing character string variable code special successful content actual more article multi-line good practical personal right name learning communication actually Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Shulou Information MySQL OPPO Reno macOS