Gita Prasetya Adiguna
Gita Prasetya Adiguna

Reputation: 389

PHP Use Array as Class's property

no matter where i search, i never found any rule that said class's property can't be an Array, but no matter how i tried, it never worked. It is against the rule to assign ARRAY as class's property? If so, is there any workaround? Here is my code

class Imperials{
protected $Data;

function __Construct($passedData){
       $this->$Data = $passedData;
       echo($this->$Data['Name']);
    }
}

$var = new Imperials(array('Name'='Buster','Race'='Nords'));

It would returned an error message

Fatal error: Uncaught Error: Cannot access empty property

Upvotes: 0

Views: 219

Answers (1)

The fourth bird
The fourth bird

Reputation: 163287

Use $this->Data without the $ instead of $this->$Data and use => for the array.

class Imperials{
    protected $Data;

    function __Construct($passedData){
        $this->Data = $passedData;
        echo($this->Data['Name']);
    }
}

$var = new Imperials(array('Name'=>'Buster','Race'=>'Nords'));

Upvotes: 10

Related Questions