对象初始化不起作用

时间:2016-07-06 15:27:43

标签: php laravel laravel-5 laravel-5.2

我只想正确初始化一个对象:

namespace App;

class Produit
{
    public $nb_serveurs;
    public $type;
    public $duree;

    public function __construct($nb_serveurs, $type, $duree){
      $this->$nb_serveurs = $nb_serveurs;
      $this->$type = $type;
      $this->$duree = $duree;
    }
}

然后在我的控制器中:

class ProductController extends Controller
{
    public function addToCard (Request $request){
      $nb_serveurs = $request->nb_serveurs;
      $type = $request->type;
      $duree = $request->duree;
      $panier = new Panier();
      $product = new Produit($nb_serveurs, $type, $duree);
      dd($product);
      $panier->addItem($product, 1);

    }
}

dd函数给我这个:

Produit {#149 ▼
  +nb_serveurs: null
  +type: null
  +duree: null
  +"2": "2"
  +"5": "5"
}

我测试了,3个变量不为空..这里有什么问题?那么Produit对象的最后两行是什么?

2 个答案:

答案 0 :(得分:2)

使用$

时,不应在变量名称中使用$this
  $this->$nb_serveurs = $nb_serveurs;
  $this->$type = $type;
  $this->$duree = $duree;

应该是

  $this->nb_serveurs = $nb_serveurs;
  $this->type = $type;
  $this->duree = $duree;

最后两个数字是因为您传递了这些值,然后创建了具有与名称相同的值的新类变量。

答案 1 :(得分:0)

你不应该在$ this之后使用$ sign。您的代码必须

    namespace App;

class Produit
{
    public $nb_serveurs;
    public $type;
    public $duree;

    public function __construct($nb_serveurs, $type, $duree){
      $this->nb_serveurs = $nb_serveurs;
      $this->type = $type;
      $this->duree = $duree;
    }
}