Reputation: 605
I am trying to add a value to the end of an array. I am using:
array_push($this->_attributes["class"],$value);
Now I know that the first parameter has to be an array. Upon inspection :
var_dump($this->_attributes["class"]); die(0);
array_push($this->_attributes["class"],$value);
I can see that the value being passed in is indeed an array as it should be. I am not sure how or why I am getting a string being passed. The output of the var_dump
look like such:
array (size=0)
empty
Why or how is $this->_attributes["class"]
being seen as a string and not an array?
Edit: If I invert the two lines like so:
array_push($this->_attributes["class"],$value);
var_dump($this->_attributes["class"]); die(0);
The var_dump looks like this:
array (size=1)
0 => string 'btn' (length=3)
This is the expected output. If I remove the var_dump, I get a fatal error on the array_push again.
** Full Class Declaration** This is enough of the class I able building for this example:
class Tag
{
protected $_attributes = array("class"=>array());
public function setAttribute($attribute,$value)
{
if( $attribute === "class" ) {
$this->setClassAttribute($value);
}
$this->_attributes[$attribute] = $value;
}
public function setClassAttribute($value)
{
if( is_array($value) ) {
foreach ($value as $c) {
$this->setClassAttribute($c);
}
return;
}
// var_dump($this->_attributes["class"]); die(0);
array_push($this->_attributes["class"],$value);
// var_dump($this->_attributes["class"]); die(0);
}
}
To execute it:
$tag = new Tag();
$tag->setAttribute("class","btn");
Upvotes: 2
Views: 1790
Reputation: 783
Your problem is here:
public function setAttribute($attribute,$value)
{
if( $attribute === "class" ) {
$this->setClassAttribute($value);
}
$this->_attributes[$attribute] = $value;
}
setClassAttribute is indeed setting the value to array("btn")
. Afterwards, it's being overwritten by the line outside the statement. Try:
public function setAttribute($attribute,$value)
{
if( $attribute === "class" ) {
$this->setClassAttribute($value);
} else {
$this->_attributes[$attribute] = $value;
}
}
php > $tag = new Tag();
php > $tag->setAttribute("class","btn");
array(0) {
}
array(1) {
[0]=>
string(3) "btn"
}
php > $tag->setAttribute("class","btn");
string(3) "btn"
Warning: array_push() expects parameter 1 to be array, string given in php shell code on line 21
string(3) "btn"
Upvotes: 1