繁体   English   中英

带有 PHP 的 ArrayObject 类的 OOP PHP

[英]OOP PHP with PHP's ArrayObject class

问题是:编写一个继承自 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。 提前致谢。

这是最简单的解决方案 -

<?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();    

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM