hamburger
hamburger

Reputation: 1425

Is it not possible to call/declare a function in an static function?

That's my Class:

class MyClass
{
    public static function test($data)
    {

       function clean($item, $key)
       {         ...do something
           }

           array_walk_recursive($data, 'clean');
 ...

I'am calling the class by:

MyClass::test("$data")

The error-message I get:

Error: [2] array_walk_recursive() expects parameter 2 to be a valid callback, function 'clean' not found or invalid function name

Upvotes: 0

Views: 163

Answers (3)

Oleg
Oleg

Reputation: 109

<?

class MyClass { 

    static function clean($item, $key) {
            echo $item.PHP_EOL;
    }

    public static function test($data)
    {        
        array_walk_recursive( $data, 'MyClass::clean'); 
    }
}

$a = [1,2,3];

MyClass::test($a);

?>

php select.php 
1
2
3

It's a solution that you need. If you don't want to use callbacks.

Upvotes: -1

iainn
iainn

Reputation: 17417

You should assign your function to a variable, and then reference that in the call to array_walk_recursive:

class MyClass
{
    public static function test($data)
    {
        $clean = function ($item, $key) {
           // do something
        };

       array_walk_recursive($data, $clean);
    }
}

$data = [1, 2, [3, 4, 5]];
MyClass::test($data);

Alternatively, just pass the callback directly, if you don't need to re-use it elsewhere:

array_walk_recursive($data, function ($item, $key) {
    // ...
});

What you've currently got will work correctly, but your clean function won't be limited to the local scope. PHP allows you to define functions at any level, but they will be created in global scope (or in the scope of any namespace you're currently using).

After the first call to MyClass::test, your code will allow calls to clean outside of the context of your static class, which may not be desirable.

Upvotes: 2

B. Desai
B. Desai

Reputation: 16436

In class as you have static method you can call function with 'self'

class MyClass_test
{
    public static function test_this($data)
    {
       array_walk_recursive($data,array("self","clean"));
     }
     public static function clean($item, $key)
     {        //Do something
     }

}
$data = array(1,2,3);
MyClass_test::test_this();

Upvotes: 0

Related Questions