Php 对象初始化不需要';行不通

Php 对象初始化不需要';行不通,php,laravel,laravel-5,laravel-5.2,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;

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

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对象中的最后两行是什么?

在使用
$this
时,不应在变量名中使用
$

  $this->$nb_serveurs = $nb_serveurs;
  $this->$type = $type;
  $this->$duree = $duree;
应该是

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

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

您不应该在$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;
    }
}