【问题标题】:how to set instance variable from inside of method and set variable name the same as its value如何从方法内部设置实例变量并将变量名称设置为与其值相同
【发布时间】:2012-11-28 12:19:51
【问题描述】:

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

【问题讨论】:

    标签: php oop scope


    【解决方案1】:

    应该是:

    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();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 1970-01-01
      • 2016-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多