Join the Stack Overflow Community
Stack Overflow is a community of 6.4 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

While I was creating a class in php, I experienced this error:

Parse error: syntax error, unexpected '[', expecting ',' or ';' on line 5 

A simple example:

<?php

class MyClass
{
  public $variable["attribute"] = "I'm a class property!";
}

?>

I already had a look at Reference - What does this error mean in PHP? but this doesn't seem to fit to my case. The problem of all other existing Questions seem to rely to an old PHP Version. But I am using PHP 5.6.3!

What can I do? Am I just sightless?

share|improve this question
    
I don't think you can do this, but try $variable = array("attribute" => "I'm a class property!") – MightyPork Jan 11 '15 at 12:45
    
I know that this way works, but why is this outside of a class possible? <?php $variable["attribute"] = "I'm a class property!"; ?> – DevTec Jan 11 '15 at 12:49
    
simply cuz it's outside of the class... it would implicitly create the array and set it's element, but here it looks like you are declaring the "attribute" element of the array as public, which is weird and php doesn't like it, too – MightyPork Jan 11 '15 at 12:50
    
Ok, a little bit confusing, but I think I get it! – DevTec Jan 11 '15 at 12:54
up vote 2 down vote accepted

You can't explicitly create a variable like that (array index). You'd have to do it like this:

class MyClass {
    // you can use the short array syntax since you state you're using php version 5.6.3
    public $variable = [
        'attribute' => 'property'
    ];
}

Alternatively, you could do (as most people would), this:

class MyClass {
    public $variable = array();

    function __construct(){
        $this->variable['attribute'] = 'property';
    }
}
// instantiate class
$class = new MyClass();
share|improve this answer

I guess you should declare it the way it is shown below :

class MyClass
{
   public $variable = array( "attribute" => "I'm a class property!" );
}
share|improve this answer

Make an array first. Use the code below

<?php

class MyClass
{
public $variable = array("attribute"=>"I'm a class property!");

}

?>

HOpe this helps you

share|improve this answer

You cannot declare class members like this. Also you cannot use expressions in class member declarations.

There are two ways to achieve what you are looking for :

class MyClass
{
    public $variable;
    function __construct()
    {
        $variable["attribute"] = "I'm a class property!";
    }
}

or like this

class MyClass
{
    public $variable = array("attribute" => "I'm a class property!");
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.