Home > Blockchain >  Multiple procedure assignment for self variable in one line
Multiple procedure assignment for self variable in one line

Time:02-01

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.

CodePudding user response:

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.

CodePudding user response:

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];
  • Related