douxingti9307 2014-01-27 13:15
浏览 108
已采纳

PHP类:如何将make方法的数据转换为类属性?

How can I turn the data from a class method into the properties of that class? Is it possible?

For instance, the article below class only has one property - $var1,

class article
{
    public $var1 = "var 1";
    public function __construct() 
    {

    }

    public function getRow() 
    {
        $array = array(
            "article_id" => 1,
            "url"       => "home",
            "title"     => "Home",
            "content"   => "bla bla"
        );

        return (object)$array;
    }
}

To get $this properties,

$article = new article();
print_r($article->var1); // var 1

To get $this method,

$row = $article->getRow();

To get $this method's data,

print_r($row->title); // Home

It works fine in that way, but how if I want to make/ move this dat**a below to the **class's properties,

            "article_id" => 1,
            "url"       => "home",
            "title"     => "Home",
            "content"   => "bla bla"

So I can just call the data like this,

$article = new article();
print_r($article->title); // Home

Is it possible?

  • 写回答

2条回答 默认 最新

  • doubu1853 2014-01-27 13:20
    关注

    You would need to use the magic __set() method to create properties that do not exists. Afterwards move the object return from the method to simple property assignation

    class article
    
    {
        public $var1 = "var 1";
        public function __construct() 
        {
            $this->getRow();
        }
    
        public function getRow() 
        {
            $this->article_id = 1;
            $this->url = 'home';
            $this->title = "Home";
            $this->content = 'bla bla';
        }
    
        public function __set($name, $value) {
            $this->$name = $value;
        }
    }
    
    $article = new article();
    echo $article->title; // prints Home
    

    If you want to save your current logic (you said move, but to be sure, you don't want to break your getRow() logic), you can move the assignation in another method (or in the constructor).

    class article
    
    {
        public $var1 = "var 1";
        public function __construct() 
        {
            foreach ($this->getRow() as $name => $value) {
                $this->$name = $value;
            }
        }
    

    Also if you don't won't anything different that the properties from getRow() to be magically used, you can unset any other assignation in your __set() method:

    $rows = (array)$this->getRow();
    if (!array_key_exists($name, $rows)) {
        unset($this->$name);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100