Web lists-archives.com

Re: [PHP] function return references to nothing




On Thu, Feb 25, 2016 at 4:35 PM, Михаил Гаврилов <
mikhail.v.gavrilov@xxxxxxxxx> wrote:

> Hi!
>
> Why function can't return references to nothing?
> In some cases wound be useful return nothing.
> Here I want show example of code which implements search leaf in tree
> and if no found path then return nothing and this correctly works.
>
>
> #!/usr/bin/php
> <?php
> function &getmultivalue(&$arr, $keys) {
>     //Begin from root
>     $value = &$arr;
>     for ($i = 0; $i < count($keys); $i++) {
>         //if not found
>         if(!isset($value[$keys[$i]])) return;
>         //Next leaf
>         $value = &$value[$keys[$i]];
>     }
>     return $value;
> }
>
> $tree = ['aaa'=>['bbb'=>['ccc'=>'ddd']]];
> print_r($tree);
> $found = &getmultivalue($tree, ['aaa', 'bbb', 'ccc']);
> if(isset($found)) {
>     $found = 'zzz';
> }
> $found = &getmultivalue($tree, ['aaa', 'bbb', 'ddd']);
> if(isset($found)) {
>     $found = '---';
> }
> print_r($tree);
> ?>
>
> =======================
>
> $ ./example.php
> Array
> (
>     [aaa] => Array
>         (
>             [bbb] => Array
>                 (
>                     [ccc] => ddd
>                 )
>
>         )
>
> )
> PHP Notice:  Only variable references should be returned by reference
> in /home/mikhail/example.php on line 8
> Array
> (
>     [aaa] => Array
>         (
>             [bbb] => Array
>                 (
>                     [ccc] => zzz
>                 )
>
>         )
>
> )
>
>
> Work as expected but I really do not like Notice "Only variable
> references should be returned by reference" which said that is my code
> is ugly.
>
> Can you suggest alternative solution or may be remove this notice in this
> case.
> Of course I am agree that impossible return constants, but i think
> nothing we could return.
>
>
> function &getValue() {
>     return 'value'; // this is not right.
> }
>
> but
>
> function &getValue() {
>     return; // this is right.
> }
>
>
>
> What do you think?
>
> Sorry if I did write to wrong mailing list. I would like that it read
> peoples who develop PHP standards.
>
>
> --
> Best Regards,
> Mike Gavrilov.
>
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
>
Is your code working as expected? In the second call it found matches when
there are no keys matching "ddd"?