skip to Main Content

I am converting an old project that uses all functions to use a class. Not all installed instances will be updated so I have to have the code work with the function or the class but I can’t get it to work. Here is an outline of the code I am using:

    function GetStatus($id) {
       return true;
    }

    class myclass (
       public function GetStatus($id) {
          return true;
       }
    }

    if (class_exists('myclass')) {
       $fcn = $myclass->GetStatus;
    } else {  
       $fcn = GetStatus;
    } 

    echo 'result = ' . $fcn($user_id);

So the code checks if the class exists and uses that method, else it uses the function. The code runs without errors but when the class method is used the return is not shown. That is, the results are

    result = 1   //when function is used
    result =     //when method is used

Is this possible? If it matters, the minimum php version is 7.1.

2

Answers


  1. Checking for a myclass existance when you already have the myclass instance stored in a $myclass variable makes no sense. Maybe you should check for a method existance?

    if (method_exists($myclass, 'GetStatus')) {
       $fcn = function($id) use ($myclass){
          return $myclass->GetStatus($id);
       };
    } else {  
       $fcn = function($id){
          return GetStatus($id);
       };
    } 
    
    echo 'result = ' . $fcn($user_id);
    
    Login or Signup to reply.
  2. To make a callable from an instance and method, you use an array containing the instance and the method name.

           $fcn = [$myclass, 'GetStatus'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search