Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何从方法内部设置实例变量,并将变量名设置为其值_Php_Oop_Scope - Fatal编程技术网

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

Php 如何从方法内部设置实例变量,并将变量名设置为其值,php,oop,scope,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

如何从方法内部设置实例变量并将变量名设置为其值?描述在代码中-请参阅从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();
应该是:

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