0

I'm trying to build a configuration class called AcmeCorpConfiguration in PHP 7.3 which will eventually be populated using data in a JSON file. However, a parse error is occurring on this line public Item $itemList = []; - it says Parse error: syntax error, unexpected 'Item' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) in C:\xampp\htdocs\PopulateObjectsFromJSONFile\version4.php on line 217. Here are the model classes:

class Item
{   
    public $itemID;
    public $description;
}

class Location
{    
    public $storeID;
    public $city;
    public $state;
}

class Fleet
{    
    public $vehicleID;
    public $type;
    public $model;
    public $year;
}

class AcmeCorpConfiguration
{
    public $company;
    public Item $itemList = [];
    public Location $locationList = [];
    public Fleet $fleetList = [];
}

Here are the contents of the JSON file:

{
    "Company":"Acme Corporation",
    "Items": [
        {"itemID":72, "description":"drill"},
        {"itemID":73, "description":"hammer"},
        {"itemID":74, "description":"pliers"}
    ],
    "Locations": [
        {"storeID":7, "city":"Omaha", "state":"NE"},
        {"storeID":9, "city":"Madison", "state":"WI"}
    ],
    "Fleet": [
        {"vehicleID":92, "type":"truck", "model":"Ford F-150", "year":2015},
        {"vehicleID":93, "type":"truck", "model":"GMC Sierra 1500", "year":2018},
        {"vehicleID":94, "type":"truck", "model":"Toyota Tundra", "year":2018},
        {"vehicleID":95, "type":"car", "model":"Toyota Lexus", "year":2019}
    ]
}

Why is it giving a parse error? I have done something similar to this in C# but perhaps the type hinting syntax or general approach isn't right for PHP.

knot22
  • 2,648
  • 5
  • 31
  • 51
  • Its in the error message *Fatal error: Property of type Item may not have default value*. So try `public Item $itemList;` – Lawrence Cherone Jun 26 '19 at 02:29
  • 1
    Also, you need >=7.4.0alpha1 to use that feature/syntax: https://3v4l.org/5NMcp#vhhvm-3101 – Lawrence Cherone Jun 26 '19 at 02:31
  • @LawrenceCherone It's not giving a Fatal error, rather a Parse error. The link you provided in your second comment was quite helpful. It looks like I'll have to wait until PHP 7.4 is available to get this to work correctly. – knot22 Jun 26 '19 at 02:37
  • Yeah had to check myself, looks new to me. Though in 7.4.0 you get the error above if you do `public Item $itemList = [];`, so might need to wait for 7.5.0 for default values. – Lawrence Cherone Jun 26 '19 at 02:41

0 Answers0