-1

This is very basic question, I have this class which says i can define my own handler which will alter the callName() function in the example below :

class MyClass
{
 protected static $callHandler;

 public static function callName($name){
        if (static::$callHandler) {
            return call_user_func(static::$callHandler, $name);
        }
     print $name;
  } 
}

I know i can do this : $class = new MyClass(); $class->callName("Jonny");

But how do I define my own $callhandler in call_user_func and alter the outcome?

San
  • 125
  • 4
  • 10
  • 1
    `MyClass::callName()` is a [static method](http://php.net/manual/en/language.oop5.static.php). You should call it as `MyClass::callName("Jonny")`. – axiac Aug 28 '17 at 08:15
  • Thanks for the answer @axiac, tell me how do i define $callHandler – San Aug 28 '17 at 08:23
  • Any function that receives one argument can be used as `$callHandler`. You have to add a (static) method to your class to set it, though. – axiac Aug 28 '17 at 08:24
  • 1
    Are you writing this class, or are you asking us how to alter `$callHandler` in this existing class…? – deceze Aug 28 '17 at 08:25
  • @deceze this is just an example, real code is very lengthy. – San Aug 28 '17 at 08:27

1 Answers1

0

These are the ways that come to my mind, you should choose the most appropriate one:

  • Check the rest of the methods of the class if some kind of setter, initializer or magic setter method exists and use it.
  • Extend MyClass and set $callHandler there.
  • Extend MyClass and create some static initialization function, which you'll call afterwards to set the value.
  • Use Reflection.

You can check these SO questions, they're similar: How to initialize static variables, Dynamically populating a static variable in PHP.

Nikolai Tenev
  • 472
  • 3
  • 8