0

如何从方法内部设置实例变量并将变量名称设置为与其值相同?描述在代码中 - 查看从 1 到 4 的步骤。

我知道我可以使用$$variable但如何使用新名称使其成为实例变量?

class Control
{
  //2. i pass the name of class and make a new object 
  function model($object)
  {
    // 3. I create here variable with the name i set. so now it should be 
   // accessible as $HomeModel but how to make it accessible for other methods. 

    $$object=new $object(); 
  }
}

class HomeController extends Control
{
  //THIS IS START
  public function __construct()
  {
    // 1. when i set the name here ['HomeModel'] and run class method model 
    $this->model('HomeModel');

    //4. and use it ie. here 
    $data=$this->HomeModel->getData();
  }
}

class HomeModel 
{
  public function getData()
  {
  echo "data";
  }
}

$x = new HomeController();
4

1 回答 1

0

应该:

class Control
{
  //2. i pass the name of class and make a new object 
  function model($object)
  {
    // 3. i want to create here an instance variable with the name i set
    $this->{$object} = new $object();
  }
}
于 2012-11-28T12:42:03.107 回答