开发者

creating fly variable

Need load parameters to function, creating a variable name on the fly terrible thing, but I do not see another solution. This code contains an error please help

<?php 

class A{

  public $vars;
  public $tab_names;

  publ开发者_如何转开发ic $tab_names = array('car'=>'audi', 'honda' => 'name');
  public $tab_fruits = array('name'=>'banana', 'banana'=>'fruit');

public function load($varr){

  $$varr;

  $this->vars = $varr;

}

public function display(){

  return  $this->vars;

}  

}

$ob = new A;
$ob->load('tab_names');
$ob->display();



?>


Like this?

public function load($varr){
  $this->vars = $this->$varr;
}


You should create separate methods to return the disparate types of data. They can be wrappers for the "real" function, if necessary:

public function displayCars() {
    return $this->tab_names;
}

public function displayFruit() {
    return $this->tab_fruits;
}

This will obviate the need for variable variables.


I don't think you can set the value of an variable at the start

public $tab_names = array('car'=>'audi', 'honda' => 'name');
public $tab_fruits = array('name'=>'banana', 'banana'=>'fruit');

which should be

public $tab_names;
public $tab_fruits;

then

class A {
    public $vars;
    public $variables;
    public $tab_names;
    public $tab_fruits;

    public function __construct($variables){
        $this->variables = $variables;
    }

    public function load($varr){
        $this->vars = $this->variables[$varr];
    }

    public function display(){
        return $this->vars;
    }  

}

$variables = array();
$variables['tab_names'] = array('car'=>'audi', 'honda' => 'name');
$variables['tab_fruits'] = array('name'=>'banana', 'banana'=>'fruit');

$ob = new A($variables);
$ob->load('tab_names');
print_r($ob->display());


This is how I would do it:

class A {
    public $loaded_vars;

    public static $vars = array(
        'tab_names' => array('car'=>'audi', 'honda' => 'name'),
        'tab_fruits' => array('name'=>'banana', 'banana'=>'fruit')
      );

    public function load( $name ){
        $this->loaded_vars = self::$vars[ $name ];
    }

    public function display() {
        return  $this->loaded_vars;
    }
}

$ob = new A;
$ob->load( 'tab_names' );
$ob->display();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜