繁体   English   中英

对象初始化不起作用

[英]Object initialization doesn't work

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

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个变量都不为null。 Produit对象的最后2行是什么?

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

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

应该

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

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

您不应在$ this之后使用$符号。 您的代码必须是

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM