How can you append a variable to a variable, to make it lookup a different name?
ie:
public function Test($var)
{
echo $this->Item->Area_$var;
die;
}
So if I did:
Test('51');
it would really do this:
$this->Item->area_51;
How can you append a variable to a variable, to make it lookup a different name?
ie:
public function Test($var)
{
echo $this->Item->Area_$var;
die;
}
So if I did:
Test('51');
it would really do this:
$this->Item->area_51;
use arrays
By using variable variables.
Although, with a better idea of what you’re wanting to achieve, a more appropriate technique may be available to you.
Technically it’s not a variable variable I’d say, but ho hum.
$this->items->area_{$var};
If you can post your real problem then there might be some better solutions rather than that. But variable variables (as Paul already suggested) is what you are tying to use. But still let us know why you are doing that. I am quite confused while you know the prefix of the variable ‘Area_’ then why not just call them directly as normal.
Test('Area_51');
But you can still append the variable like this:
class myClass{
private $a_1;
public function __construct(){
$this->a_1 = 'Test';
}
public function getM($a){
return $this->$a;
}
}
$counter = 1;
$obj = new myClass();
$v = 'a_' . $counter;
echo $obj->getM($v);
Umm… the way Anthony has posted above did not work for me before when I was also trying to do so. Anthony, can you please say why the following code does not work for me to return the text ‘Test’ though it does not give any error? What I am doing wrong in the following code?
class myClass{
private $a_51;
public function __construct(){
$this->a_51 = 'Test';
}
public function getM($a){
return $this->a_{$a};
}
}
$obj = new myClass();
echo $obj->getM('51');
But the code that I have posted in my previous post does work and that is what I had done before.
Sorry, I didn’t test it.
This works, but is probably wrong too!
The requirement to concatenate to the string surprised me.
<?php
class HTMLSpecificationFinder
{
protected
$html4 = 'Version 4',
$html5 = 'Version 5';
public function getSpec($version){
return $this->{'html' . $version};
}
}
$obj = new HTMLSpecificationFinder();
echo $obj->getSpec(5); #Version 5
?>
Its hard to explain
there are a lot of different $pageTypes, and want to grab that groups settings ie:
$this->Settings->notify_subj_{$PageType}
$this->Settings->notify_msg_{$PageType}
I could do a switch statement but I think that would remove the flexibility of it.
Oh… I don’t want to say that it is wrong but I had tried rest of the other ways except this one:
$this->{'html' . $version};
Thank you Anthony!