PHP自定义类数组

时间:2011-04-28 15:01:40

标签: php arrays

我正在尝试创建一个自定义类并拥有这些对象的数组,而我似乎无法让它工作。这是我的代码:

class NavigationItem
{


private $_filename;
private $_linkname;

public function __construct($filename, $linkname)
{
    parent::__construct();

    $this->_filename = $filename;
    $this->_linkname = $linkname;
}

public function getFilename()
{
    return $_filename;  
}

public function getLinkname()
{
    return $_linkname;  
}
}

$navInfo = array();

$size = array_push($navInfo, new NavigationItem("index.php","HOME"),
                                  new NavigationItem("about.php","ABOUT"),
                                  new NavigationItem("coaches.php","STAFF"),
                                  new NavigationItem("summer.php","SUMMER 2011"),
                                  new NavigationItem("fall.php","FALL 2011"),
                                  new NavigationItem("history.php","HISTORY"),
                                  new NavigationItem("contact.php","CONTACT"));

echo "<table>";
echo "<tr>";
echo "<td colspan=\"7\" height=\"125px\"><img src=\"images/banner_blue_skinny.jpg\" alt=\"\" /></td>";
echo "</tr>";
echo "<tr>";

for($i=0; $i<$size; $i++)
{
echo "<td class=\"linkCell\"><a class=\"navigation\" href=\"" . $navInfo[$i]->getFilename() . "\">" . $navInfo[$i]->getLinkname() . "</a></td>";
}

echo "</tr>";

echo "<tr>";
echo "<td colspan=\"7\" class=\"gapCell\"></td>";
echo "</tr>";
回声“”; echo“”;

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

$this用于表示类方法中的类对象,应该用于访问属性并在同一类的其他方法中调用方法。

public function getFilename()
{
    return $this->_filename;  
}

从类的构造函数中删除父构造的调用,因为它不是从任何其他类继承的

//parent::__construct();

答案 1 :(得分:4)

class NavigationItem
{

    private $_filename;
    private $_linkname;

    public function __construct($filename, $linkname)
    {
        $this->_filename = $filename;
        $this->_linkname = $linkname;
    }

    public function getFilename()
    {
        return $this->_filename;  
    }

    public function getLinkname()
    {
        return $this->_linkname;  
    }
}

要访问类属性,必须使用$this->(例如,不像Java中那样)。

为了更好的可重复性,您可以缩进代码。 parent::__construct()也没用,因为你没有从另一个类继承。

现在对于阵列的使用,只有一些技巧(IMO)使它更具可读性:

$navInfo = array(
    new NavigationItem("index.php","HOME"),
    new NavigationItem("about.php","ABOUT"),
    new NavigationItem("coaches.php","STAFF"),
    new NavigationItem("summer.php","SUMMER 2011"),
    new NavigationItem("fall.php","FALL 2011"),
    new NavigationItem("history.php","HISTORY"),
    new NavigationItem("contact.php","CONTACT")
);

foreach ($navInfo as $item) {
    echo $item->getFilename() . "..." . $item->getLinkname();
}

使用foreach,您不需要知道数组的大小,只需遍历每个项(您不关心项的索引)。