如何从方法内部设置实例变量,并将变量名称设置为与其值相同

时间:2012-11-28 12:19:52

标签: php oop scope

如何从方法内部设置实例变量,并将变量名设置为与其值相同?描述在代码中 - 查看从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();

1 个答案:

答案 0 :(得分: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();
  }
}