Pregunta

There is a property $modelName in class A that is accessed in this class using $this->modelName.

This property contains a name of another class B.

I want to call a static method of class B not creating an object of B.

Working code:

$b = $this->modelName;
$b::model()->findAll();

Question: How to call model()->findAll() not using $b?

I tried $this->modelName::model()->findAll(); but it’s not working.

¿Fue útil?

Solución

Do it:

 class A{
   public $modelName = 'B';

   function callB(){
     call_user_func(array($this->modelName, 'model'))->findAll();
   }
 }

 class B{
   private  static $model = null;

   static function model(){

     if (!self::$model) {
        self::$model = new B();
     }
     return self::$model;
  }

   function findAll(){
      print  __CLASS__.' method `findAll()`';
   }
 }

$A = new A;
$A->callB();

// B method `findAll()`
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top