Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If the variable is null or not assigned, putting value in function does not work

Tags:

php

I have this function that sometimes does not assign the variable $infolasterroredu

In these cases I want to tell the function to assign the value "Hello" if the variable is not assigned or is null.

I tried this way but it keeps returning the value "null" when the variable is not assigned.

How would I put a default value? I've tried all the options and nothing seems to work.

private static function stockstatus(Product $product, $infolasterroredu = 'Hello')
{
//my function code
}

The result of this code is null when debugging, what am I doing wrong?

I call the function like this self::stockstatus($product, $infolasterroredu);

I know this can be solved this way self::stockstatus($product, $infolasterroredu ?: "Hello");

But this would take editing all the function calls which are several so I need to do it by direct function.

Note: When I say direct function, it means directly putting the value in the private static function and not editing the calls to the function line by line, which are too many.

like image 990
Club Avatar asked Nov 29 '25 02:11

Club


1 Answers

By not having a type at all on the second argument, you're saying anything can be passed, but if nothing is passed (not even null), it's Hello. First, I would restrict the type if possible:

function stockstatus(Product $product, string $infolasterroredu = 'Hello') {}

This doesn't solve if '' (empty string) is passed in. You could "solve" this problem with a call-side default that passes in Hello if not present:

stockstatus($product, $infolasterroredu ?: 'Hello')

The problem I see with this is that it gives an internal concern for the function to some other caller, which makes the call more brittle in case the function itself changes.

Instead, I would set it up to allow a null switch but require a string, and default internally:

function stockstatus(Product $product, ?string $infolasterroredu = null) {
    $infolasterroredu = $infolasterroredu ?: 'Hello';

    ...
}

I'm using ?: to catch any empty or nulled value and default it to Hello. You can put 'Hello' in the default in the argument expression (this may help with type assist). However, I prefer to have someone read the function if they don't know how to call it, and I'm not duplicating the actual default value twice (in the argument default and in the internal check).

One downside, if you will, is that this accepts any truthy string, even, say or .. The best practice way of handling this is to use a value object with validation on the setter (or even a default non-thrown exception) as the second argument.

like image 183
Jared Farrish Avatar answered Dec 01 '25 18:12

Jared Farrish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!