user1472065
user1472065

Reputation: 115

PHP Array Not Accepting Variables Correctly

I have an array in PHP where some of the inputs are just literal strings while one input has a variable inserted. I am getting an error that says "syntax error, unexpected "", expecting ')' on line 66". This doesn't make sense to me as it is simply an array of strings, and I hadn't closed the array or done anything funky yet.

Here is my code.

private $headerLink;

private $header = array(
    "<header>",
    "\t\t<h1><a href=$headerLink>Daily Drop</a></h1>",
    "\t</header>"
);

$headerLink is initialized in the constructor so it is not because it is empty. I even tried just setting it to be "test" to make sure that wasn't it but it did not work.

Does anyone know what is causing this error and how to fix it?

Thanks so much!

Upvotes: 0

Views: 51

Answers (2)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

When you initialize variable you cannot use expressions and use other variables.

But if you want to set $header value using $headerLink you could move some code to contructor.

You can do it for example this way:

private $header = array(
    "<header>",
    "\t\t<h1><a href=[header_link]>Daily Drop</a></h1>",
    "\t</header>"
);

public function _construct() {
    // here other constructor tasks  
    $this->header[1] = str_replace('[header_link]', $this->$headerLink, $this->header[1]);
}

However probably the best solution would be simple creating new method and then:

private $header;

public function _construct() {
    // here other constructor tasks  
    $this->setHeader($this->headerLink);

}

private function setHeader($headerLink) {
    $this->header = array(
        "<header>",
        "\t\t<h1><a href=$headerLink>Daily Drop</a></h1>",
        "\t</header>"
    );
}

Upvotes: 0

Marc B
Marc B

Reputation: 360702

Object attributes must be initialized with fixed/constant values. They cannot be the result of an expression:

private $foo = 'bar'; // ok.
private $bar = 'baz' . 'qux'; // bad, this is an expression
private $baz = 'foo' . $foo;
// also bad - expression + undefined variable, should be $this->foo anyways

In your case:

php > class foo { private $foo = array('foo', $bar, 'baz'); }
PHP Parse error:  syntax error, unexpected T_VARIABLE, expecting ')' in php shell code on line 1
php > class foo { private $foo = array('foo', 'bar', 'baz'); }
php >

Upvotes: 4

Related Questions