0

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.

ProtectedVoid
  • 1,293
  • 3
  • 17
  • 42

2 Answers2

1

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

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

Since we no longer need to call count(), we can avoid the problem of needing the same intermediate value in two places.

Whether the result is actually more readable than using two lines of code is a matter of taste - remember that a program is as much for human use as for machine use.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • Thanks for the answer. This worked on this specific case, which is great but the question was targeted for a global use. This answer suggests that it can only be accomplished if a function that returns a single-element array is used, and depending on the data type. – ProtectedVoid Feb 03 '23 at 13:05
  • @ProtectedVoid I guess the answer is more saying you should try to avoid situations where you _need_ to do that: either just use multiple lines of code and an intermediate variable, or take a different approach to the problem. The solution is not using the same calculated value twice, it's just avoiding the `count()` call so that it doesn't need to. – IMSoP Feb 03 '23 at 13:06