How to update reference argument in functions in PHP

Viewed 23

If I have two functions, both with arguments that include a reference to a string. One function will call the other, but both functions could have the ability to set value of the referenced variable.

Currently, the below code will keep the variable as NULL instead of updating the variable. I know for sure that reason is being set, because I can breakpoint where it's setting reason (and even output reason in the current scope).

function function_a(string $path, ?string &$reason = null): ?string {
    // Set to false for example purposes
    $checkIsValid = false;
    if(!$checkIsValid) {
        $reason = 'Reason why it is invalid';

        return null;
    }

    return function_b($path, $reason);
}

function function_b(string $path, ?string &$reason = null): ?string {
    $anotherValidCheck = false;
    if($anotherValidCheck) {
        $reason = 'Another reason why it is invalid';

        return null;
    }

    return 'Some value';
}

There's also core PHP function that's using similar functionality to what I'm attempting to achieve (output argument in the exec function). Another example is the out keyword in .NET. I'm guessing since PHP references aren't quite like your typical reference, that this won't work?

1 Answers

Although I hadn't specified in my original question, I am using Laravel facades. For some reason, using a reference how I wanted didn't work with the Facade. Perhaps because of how it's overridding __call with the Macroable trait.

Using DI to use the repository class instead of the facade fixed the issue for me.

Anyway, hopefully this might help anyone else that comes across this issue.

Related