简体   繁体   中英

Multiple procedure assignment for self variable in one line

Is there any way a variable can be assigned from multiple procedures in one line?

For example:

$class_splits = explode("\\", $class_name);
$short_class_name = $class_splits[count($class_splits) - 1] ?? null;

Translated to this pseudo code:

$short_class_name = explode("\\", $class_name) => prev_result(count(prev_result) -1);

I don't have big expectations on this as I know it looks too "high-level" but not sure if newer versions of PHP can handle this.

Thanks.

You can use an assignment as an expression, then refer to the variable that was assigned later in the containing expression.

$short_class_name = ($class_splits = explode("\\", $class_name))[count($class_splits) - 1] ?? null;

That said, I don't recommend coding like this. If the goal was to avoid creating another variable, it doesn't succeed at that. It just makes the whole thing more complicated and confusing.

I believe you have an "X/Y Problem": your actual requirement seems to be "how to split a string and return just the last element", but you've got stuck thinking about a particular solution to that.

As such, we can look at the answers to " How to get the last element of an array without deleting it? " To make it a one-line statement, we need something that a) does not require an argument by reference, and b) does not require the array to be mentioned twice.

A good candidate looks like array_slice , which can return a single-element array with just the last element, from which we can then extract the string with [0] :

$short_class_name = array_slice(explode("\\", $class_name), -1)[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM