hydrogen18
January 1st, 2009, 11:01 PM
Is it possible to create an array of objects in PHP? I seem to be able to do it successfully in a statically referenced way like
$myobj[3] = new object("Hi!");
However in this snippet of code where I am accessing a portion of the array based on a variable specifying an index I get an error of
Fatal error: Call to a member function getTextHTMLlink() on a non-object in /var/www/navmenu.php on line 22
Here is the code with the associated line in bold
<?php
class navMenu{
protected $numItems=-1;
protected $items=array();
protected $title=0;
function __construct($ptitle){
$this ->title = $ptitle;
}
function addItem($itemTitle, $itemUrl){
$this->numItems++;
echo "navMenuItem added! numItems is now " . $this->numItems;
$this->items[$this->numitems] = new navMenuItem($itemTitle,$itemUrl);
} //additem
function toHTMLTable(){
$table = "<table><tr><td>" . $this->title . "</td></tr>";
for($counter=0; $counter<=$this->numItems;$counter++){
$table .= "<tr><td>";
$table .= $this->items[$counter]->getTextHTMLlink();
$table .= "</td></tr>";
}
$table .= "</table>";
return $table;
}
}
class navMenuItem{
protected $text=0;
protected $url=0;
protected $imageUrl=0;
function __construct($ptext, $pUrl){
$this->text = $ptext;
$this->url = $pUrl;
}
function getText(){
return $this->text;
}
function getUrl(){
return $this->url;
}
function getImageUrl(){
return $this->imageUrl;
}
function getTextHTMLlink(){
$link = "<a href='" . $this->url . "'>" . $this->text . "</a>";
return $link;
}
}
?>
What am I doing wrong?
$myobj[3] = new object("Hi!");
However in this snippet of code where I am accessing a portion of the array based on a variable specifying an index I get an error of
Fatal error: Call to a member function getTextHTMLlink() on a non-object in /var/www/navmenu.php on line 22
Here is the code with the associated line in bold
<?php
class navMenu{
protected $numItems=-1;
protected $items=array();
protected $title=0;
function __construct($ptitle){
$this ->title = $ptitle;
}
function addItem($itemTitle, $itemUrl){
$this->numItems++;
echo "navMenuItem added! numItems is now " . $this->numItems;
$this->items[$this->numitems] = new navMenuItem($itemTitle,$itemUrl);
} //additem
function toHTMLTable(){
$table = "<table><tr><td>" . $this->title . "</td></tr>";
for($counter=0; $counter<=$this->numItems;$counter++){
$table .= "<tr><td>";
$table .= $this->items[$counter]->getTextHTMLlink();
$table .= "</td></tr>";
}
$table .= "</table>";
return $table;
}
}
class navMenuItem{
protected $text=0;
protected $url=0;
protected $imageUrl=0;
function __construct($ptext, $pUrl){
$this->text = $ptext;
$this->url = $pUrl;
}
function getText(){
return $this->text;
}
function getUrl(){
return $this->url;
}
function getImageUrl(){
return $this->imageUrl;
}
function getTextHTMLlink(){
$link = "<a href='" . $this->url . "'>" . $this->text . "</a>";
return $link;
}
}
?>
What am I doing wrong?