penu
penu

Reputation: 1040

string arrays within strings

Why is this a compile error:

<?php
class Bean
{
    public $text = array("123", "456");
    public $more = array("000 {$this->text[0]} 000", "--- {$this->text[1]} ---");

}

?>

The compiler says PHP Parse error: syntax error, unexpected '"'

How can I use my text array within my other arrays?

Upvotes: 0

Views: 75

Answers (3)

Ren&#233; H&#246;hle
Ren&#233; H&#246;hle

Reputation: 27295

What you do in that line:

public $more = array("000 {$this->text[0]} 000", "--- {$this->text[1]} ---");

is not working in PHP.

http://php.net/manual/en/language.oop5.properties.php

here you can see valid and invalid values for properties in that example. So if you use double quotes PHP try to resolve the string.

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double

So you have to replace your " with ' then it should work

public $more = array('000 {$this->text[0]} 000)', '(--- {$this->text[1]} ---)');

what you can do is to set a placeholder in that variable and replace them before you need them with vsprintf for example.

Upvotes: 1

VolkerK
VolkerK

Reputation: 96159

As mentioned earlier you can't do that (directly) with current versions of php. Even the new features of php 5.6 won't allow that, see http://php.net/manual/en/migration56.new-features.php
But let's assume you have a valid intrest in this, like e.g. keeping/grouping something in the more declarative section of the class than hiding it somewhere in a pile of code, you could do something ( maybe a "bit" more sophisticated ;-) ) like

<?php
class Bean
{
    public $text = array("123", "456");
    public $more = array('000 %1$s 000', '--- %2$s ---');

    public function Bean() {
        foreach($this->more as $k=>&$v) {
            $v = vsprintf($v, $this->text);
        }
    }
}

$b = new Bean;
print_r($b->more);

Upvotes: 3

Tikkes
Tikkes

Reputation: 4689

You could do this:

class Bean
{
public $text = array("123", "456");

public function fillMore () {
    $more = array();
    $more[0] = "000 ".$this->text[0]." 000";
    $more[1] = "000 ".$this->text[1]." 000";

    var_dump($more);
}
}

$bean = new Bean();
$bean->fillMore();

Alternatively you could try and fill the $more in your constructor too. This will get you your $more when you initialize the class.

Upvotes: 0

Related Questions