2015-10-08 2 views
0

Я пытаюсь сократить код класса API, что я хочу сделать, чтобы убедиться, что метод существует до вызова метода внутри класса.Динамически проверять доступный метод перед запуском

Будет передан метод в качестве переменной, чтобы увидеть, существует ли этот метод внутри класса, а затем запустить метод.

Пример кода ниже:

<?php 
    class Test { 

    private $data; 
    private $obj; 

    public function __contruct($action,$postArray) 
    { 

     $this->data = $postArray; 

     if (method_exists($this->obj, $action)) { 
      //call method here 
      //This is where it fails 
      $this->$action; 
     }else{ 
      die('Method does not exist'); 
     } 

    } 

    public function methodExists(){ 
     echo '<pre>'; 
     print_r($this->data); 
     echo '</pre>'; 
    } 

} 

//should run the method in the class 
$test = new Test('methodExists',array('item'=>1,'blah'=>'agadgagadg')); 

//should die() 
$test2 = new Test('methodNotExists',array('item'=>1,'blah'=>'agadgagadg')); 
?> 

даже возможно ли это?

ответ

0

У вас есть опечатка в имени вашей функции конструктора и второй, при вызове функции method_exists() вы должны передать $this в качестве первого параметра, а не $this->obj:

public function __construct($action,$postArray) 
    { 

     $this->data = $postArray; 
     if (method_exists($this, $action)) { 
      $this->{$action}(); 

     }else{ 
      die('Method does not exist'); 
     } 
    } 
Смежные вопросы