解析错误:语法错误,意外的'__construct'(T_STRING),期望函数(T_FUNCTION)或const(T_CONST)

问题描述:

我有这个问题.当我点击添加到购物车按钮时,出现错误:

I have this problem. When I click on add to cart button there is an error:

解析错误:语法错误,意外的'__construct'(T_STRING), 期望函数(T_FUNCTION)或const(T_CONST)

Parse error: syntax error, unexpected '__construct' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

我是Laravel的新手,我真的不知道该做什么,

I'm new in Laravel and I really have no idea what I have to do,

这是我添加到购物车上的按钮上的代码:

This is my code on button add to Cart:

<a href="{{route('get.addToCart',[$product->id])}}" class="cart-btn">Add to cart</a>

这是我的路线:

Route::get('add-to-cart/{id}', 'WebController@addToCart')->name('get.addToCart');

我在webcontroller中拥有的

This I have in webcontroller:

public function addToCart(Request $request, $id){
   $product = Product::find($id);
   $oldCart = Session::has('cart') ? Session::get('cart') : null;
   $cart = new Cart($oldCart);
   $cart->add($product,$product->id);
   $request->session()->put('cart',$cart);
   dd($request->session()->get('cart'));
   return redirect()->route(get.product);
}

这是我的cart.php

<?php
namespace App;
class Cart{
   public $items=null;
   public __construct($oldCart){
      if($oldCart){
        this->$items=$oldCart->items;
      }
   }
   public function add($item,$id){
      $storedItem= ['name'=>$item];
      if(this-> $items)
      { 
         if(array_key_exists($id, this->$items)){
           $storedItem=this->$items[$id];
         }
      }
      this->$items[$id]=$storedItem;
   }
}

您的__construct需要在其前面加上单词function,或者更好的是public function

Your __construct needs to have the word function in front of it, or better yet public function

将行更改为:

public function __construct($oldCart)

在此处阅读:第8行