PHP自定义类数组

rpl*_*orn 2 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>";
Run Code Online (Sandbox Code Playgroud)

echo""; echo"";

有任何想法吗?

Sha*_*ngh 5

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

public function getFilename()
{
    return $this->_filename;  
}
Run Code Online (Sandbox Code Playgroud)

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

//parent::__construct();
Run Code Online (Sandbox Code Playgroud)


Mat*_*oli 5

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;  
    }
}
Run Code Online (Sandbox Code Playgroud)

要访问类属性,您必须使用$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();
}
Run Code Online (Sandbox Code Playgroud)

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