Jayakrishnan
Jayakrishnan

Reputation: 1335

check if function is defined on child class only

 <?php 
    class controller
    {
     public  function view()
      {
        echo "this is controller->view";
      }

}
class home extends controller
{
  public function index()
  {
    echo "this is home->index";
  }
  function page()
   { 
    echo "this is home-> page";
   }

}


$obj= new home;

$method="index";// set to view or page
if(method_exists($obj,$method))
{
 $obj->{$method}();
}

?>

my problem :
If we set $method to view, the view() from base controller class will be called.
i want to check if $method exist on home class only (don't want to check if the function is defined in base class )
any idea how this can be implimented?

Upvotes: 2

Views: 743

Answers (2)

n0nag0n
n0nag0n

Reputation: 1668

Based off of @vignesh's answer, I needed to use is_callable() to make it work.

abstract class controller {
   private function view() {
      echo "this is controller->view";
   }
}

class home extends controller {
    public function index() {
        echo "this is home->index";
    }
  
    public function page() { 
        echo "this is home->page";
    }
}

$home_controller = new home;
is_callable([ $home_controller, 'view']); // false

Upvotes: 0

Vignesh Bala
Vignesh Bala

Reputation: 919

Define base class function as private.

Change

public  function view()
      {
        echo "this is controller->view";
      }

to

private  function view()
      {
        echo "this is controller->view";
      }

It will be work...

EDIT

function parent_method_exists($object,$method)
{
    foreach(class_parents($object) as $parent)
    {
        if(method_exists($parent,$method))
        {
           return true;
        }
    }
    return false;
}

if(!(method_exists($obj,$method) && parent_method_exists($obj,$method)))
{
    $obj->{$method}();
}

This will working perfectly in your case...

Also refer this link

Upvotes: 6

Related Questions