Reputation: 1040
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
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
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
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