首页 > 解决方案 > 如何输出由 php 类设置的数组的值?

问题描述

我希望有人可以帮助我解决我的问题。我仍然是 PHP 的初学者,非常抱歉。我的代码如下所示:

class Component
{
    public $title;

    // value if nothing gets set
    public function __construct($title = "Test") {
        $this->title = $title;
    }

    public function setTitle($value)
    {
        $this->title = $value;
    }

    public function getTitle()
    {
        return "Title: ".$this->title;
    } 

    public function returnInfo()
    {
        $info = array(
        'Titel'         => $this->title,            
        );      

        return $info;
    }

所以在“组件”类中,函数应该设置并获得一个特定的值。如果没有为 ae 标题设置任何内容,它应该得到值“Test”。使用 returnInfo() 应该返回标题等信息。

我的其他类(有人可以添加标题等信息)如下所示:

abstract class ComponentInfo extends Component
{
    protected function getComponentInfo ()
    {
        $button1 = new Component;
        $button1->setTitle("Button-Standard");

        // should return all infos for button1
        $button1Info = $button1->returnInfo();

        foreach ($button1Info as $info)
        {
            echo ($info);
        }
    }
}

所以它应该像这样工作:在另一个名为 ComponentInfo 的类中,用户可以添加一个像按钮一样的组件。然后用户可以设置标题等信息。之后,信息应该保存在一个数组中,现在我想显示所有信息,如下所示:

标题:按钮-标准

它如何工作?我的代码中的错误在哪里?

获得一个工作代码会很有帮助,用户可以在其中创建他想要的尽可能多的 ComponentInfo 类,并且他可以在其中添加具有可以保存到数组中的信息的不同组件。

最后,它应该在主页上作为文本输出。

标签: phparraysclassoop

解决方案


您不能实例化抽象类。您需要abstract从类中删除关键字ComponentInfo

更新给定您评论中的信息,我会这样做

Component.php

abstract class Component
{
    private $key;
    private $title;

    public function __construct($key, $title) {
        $this->setKey($key);
        $this->setTitle($title);
    }

    public function setKey($key)
    {
        $this->key = $key;
    }

    public function getKey()
    {
        return $this->key;
    } 

    public function setTitle($title)
    {
        $this->title = $title;
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function __toString()
    {
        return $this->getKey().': '.$this->getTitle();
    }

}

ComponentInfo.php

class ComponentInfo extends Component
{
    public function __construct($key='Info', $title='example title')
    {
        parent::__construct($key, $title);
    }
}

然后在你的代码中使用它 somefile.php

$components = [];
$components []= new ComponentInfo();
$components []= new ComponentInfo('Different Key', 'Other info');
$components []= new ComponentNavigation('longitude', 'latidude'); //create another class like ComponentInfo

[... later you want to print this info in a list for example]

echo '<ul>';
foreach($components as $components) {
    echo '<li>'.$component.'</li>'; //the __toString() method should get called automatically
}
echo '</ul>'; 

这应该可行,但是,除了不同的标题和键之外,没有其他特殊性的不同组件是没有意义的。相反,您可以简单地Component使用具有不同键和标题的不同 s。


推荐阅读