Does the class designer create new class fields with variable names?
I am trying to initialize a class through a constructor using PHP 5.5.13 but I am getting some strange results. The setup is as follows:
class foo{
public $bar;
public $top;
public $bot = array();
function __construct($bar, $top){
$this->$bar = $bar;
$this->$top = $top;
}
}
$phonebook = array();
$user_input = $_POST['query'];
if(/* regex match */){
foreach($valid_input[0] as $arr){
$name_and_number = explode(" ", $arr);
$phonebook[] = new foo($name_and_number[0], (int) $name_and_number[1]); //e.g. Bob, 123
var_dump($phonebook[count($phonebook)-1]);
}
}
Now the weird part now, however, is that the var_dump phonebook returns:
object(foo)#1 (5) { ["bar"]=> NULL ["top"]=> NULL ["bot"]=> array(0) { }
["Bob"]=> string(3) "Bob" ["123"]=> int(123) }
Duration:
echo "$phonebook[0]->$bar";
echo "$phonebook[0]['Bob']"; //Since a Bob field apparently exists?
echo "$phonebook[0]->$Bob"; //Just to test if maybe a $Bob variable has been declared?
All return a blank page. I'm at a loss here. Is my constructor set up strange? Or is the way I am trying to access the variables?
source to share
What you need to do is get rid of the second character $
this way
class foo{
public $bar;
public $top;
public $bot = array();
function __construct($bar, $top){
$this->bar = $bar;
$this->top = $top;
}
}
The reason you see "strange" results is that the value is $bar
both $top
evaluated dynamically and will be used to create a new named property. As a result, in your case, a property named "Bob" and "123"
source to share
The problem is these lines:
function __construct($bar, $top){
$this->$bar = $bar;
$this->$top = $top;
}
$this->$bar
refers to the property named after bar. So if you pass in a name Bob
, you are actually setting the property to a Bob
value 'Bob'
.
Your intention, of course, is to set the property bar
. To do this, remove the sign $
. It should be omitted for properties:
$this->bar = $bar;
So it has nothing to do with the constructor, it's just the way you use properties anywhere. In the constructor or even outside of the class methods. echo "$phonebook[0]->$bar"
should also be echo "$phonebook[0]->bar";
.
Personally, I think this is a strange and contrasting intuitive syntax, but I was once in a serious fight with it with the PHP affiniad, so I dare not bring it up again. Just live with him.;)
source to share