Samyoul Samyoul - 1 month ago 6
PHP Question

Why do some php functions 'return' a given parameter?

I'm not sure if I've phrased this question appropriately but I don't know how else to pose it without giving examples, which I will do.

Examples:

preg_match

preg_match("/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/", $input_line, $output_array);


Why do we give preg_match the parameter of
$output_array
? It seems not to make sense in the context of how the rest of php works. Wouldn't the following be more conventional?

$output_array = preg_match("/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/", $input_line);





openssl_private_encrypt

openssl_private_encrypt ($data , $encrypted_data , $key);


Again, why do we pass the
$encrypted_data
to the function? Rather than what 99% of other functions do and return the result which can be used to set a variable's value.

$encrypted_data = openssl_private_encrypt ($data, $key);





Is this a legacy issue? Are there good reasons for doing this with certain functions?

Answer

Since PHP isn't big on throwing exceptions in the good old core standard library, it needs a different mechanism to distinguish two aspects of a function's operation:

  • did the operation succeed?
  • what's the return value, if any?

Languages which build more on exceptions would have something like this:

try:
    value = somefunc()
except SomeError:
    # handle failure

Languages like Go return a return value and an error status indicator:

value, err := somefunc()
if err != nil {
    log.Fatal(err)
}

PHP instead uses the return value as the success indicator and a by-reference parameter as return value, especially when that return value is not always of interest:

if (!somefunc($value)) {
    // handle failure
}
echo $value;

Otherwise code would have to look something like this:

$value = somefunc();
if ($value === false) {
    // handle failure
} else if ($value === 0) {
    // no match
}
echo $value;

In some cases using the return value both for error indication and return value is impossible, since false or 0 or both may be a legitimate return value and you couldn't distinguish it from an error code. Using by-reference parameters for "secondary" return values is not a terrible design decision, if you're not going to use exceptions.

Comments