PHP static recursive method

Is it possible to perform a recursion using 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 get this error on execution:

Severity Level: Warning

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

Thank!

+4
source share
3 answers

try it

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

array_map enable callable.

You can try it with magic constants

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

Or using self

return array_map([self, __METHOD__], $obj);
+3
source

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);
+2
source

:

return array_map('self::objectToArray', $obj);

//

return array_map(array(self, 'objectToArray'), $obj);

( json-, ):

class Helpers {
     public static function objectToArray($obj) {
         return json_decode(json_encode($obj), true);
     }
}
+1

Source: https://habr.com/ru/post/1531698/


All Articles