Geetha Infotech
Geetha Infotech

Reputation: 11

how to change static method in php outside class

We can change the static variable value of a class from outside, thats the advantage of static variables but how do we change static method from outside ?

<?php

class A
{
   static $static_var = 0;   

   static function test(){
      return 'i want to change inside this test method';
   }
}
echo A::$static_var; // outputs 0

++A::$static_var;

echo A::$static_var; // ouputs 1

// Now how do we do something to change the static test method body? is it possible ?
like

A::test() = function(){ /* this is wrong */} 

}

Upvotes: 1

Views: 2188

Answers (1)

Bang
Bang

Reputation: 929

As @Mark Baker said, you can only change variable... But there is a way to declare variable as callable, you can use anonymous function.

here is the documentation: http://php.net/manual/en/functions.anonymous.php

class A
{
   public static $method;
}

A::$method = function() { 
    echo 'A'; 
};

call_user_func(A::$method);
// OR
$method = A::$method;
$method();

Upvotes: 3

Related Questions