使用PHP的ArrayObject类

时间:2015-07-31 15:35:44

标签: php oop

问题是: 编写一个继承自PHP的ArrayObject类的PHP类。为新类提供一个名为displayAsTable()的公共函数,它将所有设置的键和值作为HTML表输出。实例化此类的实例,为对象设置一些键,并调用对象的displayAsTable()函数将数据显示为HTML表。

我的回答是:

<?php

class View
{
    //definition
    private $id;
    private $name;
    private $email;

    /*
     * Constructor
     */
    public function __construct($id, $name, $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }

    /*
     * get ID
     */
    public function getId()
    {
        return $this->id;
    }

    /*
     * get Name
     */
    public function getName()
    {
        return $this->name;
    }

    /*
     * get Email
     */
    public function getEmail()
    {
        return $this->email;
    }
}


// New View List Class which extends arrayObject in PHP
class ViewList extends ArrayObject
{
    /*
     * a public function to return data
     */
    public function displayAsTable() // or you could even override the __toString if you want.
    {
        $sOutput = '<table border="1"><tbody>';
            foreach ($this AS $user)
            {
                $sOutput .= sprintf('<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
                    $user->getId(),
                    $user->getName(),
                    $user->getEmail()
                );
            }
            $sOutput .= print '</tbody></table>';

        return $sOutput;
    }

    /*
     * return data to string
     */
    public function __toString()
    {
        return $this->displayAsTable();
    }
}

/*
 *  data(s)
 */
$data = new ViewList();
$data[] = new View(1, 'Selim Reza', 'me@selimreza.com');
$data[] = new View(2, 'Half Way', 'selimppc@gmail.com');

/*
 * final output
 */
print $data;

但我认为我缺少用于打印的2D和3D阵列。 请帮助我如何以html格式打印2D和3D(在表格中)。在此先感谢。

1 个答案:

答案 0 :(得分:0)

这是最简单的解决方案-

<?php   

class InheritArrayObject extends ArrayObject {

    // inherits function from parent class
    public function __set($name, $val) {
        $this[$name] = $val;
    }

    public function displayAsTable() {
        $table =  '<table>';
        $table .= '<tbody>';    
        $all_data = (array) $this;
        foreach ($all_data as $key => $value) {
            $table .= '<tr>';
            $table .= '<td>' . $key . '</td>';
            $table .= '<th>' . $value . '</th>';
            $table .= '</tr>';
        }    
        $table .= '</tbody>';
        $table .=  '</table>';    
        return $table;
    } 
}

$obj = new InheritArrayObject();    
$obj->Name = 'John Doe'; 
$obj->Gender = 'Male'; 
$obj->Religion = 'Islam'; 
$obj->Prepared_For = 'ABC Org';

echo $obj->displayAsTable();    

?>