Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP static method recursive

Is it possible to do a recursion on a static method?

    class Helpers {
         public static function objectToArray($obj) {
            if (is_object($obj)) {
                $obj = get_object_vars($obj);
            }

            if (is_array($obj)) {
                return array_map(__FUNCTION__, $obj);
            }
            else {
                return $obj;
            }
         }
    }

I'm getting this error when executed:

Severity: Warning

Message: array_map() expects parameter 1 to be a valid callback, function 'objectToArray' not found or invalid function name.

Thanks!

like image 288
basagabi Avatar asked Feb 14 '23 12:02

basagabi


2 Answers

You can recursively call a static method. The following code, for example, will work fine:

<?php 

class MyClass{
    public static function test($count)
    {       
        if ($count < 10) {
            $count++;
            self::test($count);
            
            echo $count;                
        }
    }
}

MyClass::test(0);
like image 151
Mahbub Avatar answered Feb 16 '23 04:02

Mahbub


Try this

return array_map(['Helpers', 'objectToArray'], $obj);

array_map permit callable type.

You could try it with magic constants

return array_map([__CLASS__, __METHOD__], $obj);

Or using self

return array_map([self, __METHOD__], $obj);
like image 43
sectus Avatar answered Feb 16 '23 03:02

sectus