【问题标题】:PHP class: how to a make method's data to become the class properties?PHP 类:如何使方法的数据成为类属性?
【发布时间】:2014-01-27 13:15:28
【问题描述】:

如何将 data 从类method 转换为该类的properties?有可能吗?

例如,article 下面的类只有一个属性 - $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;
    }
}

要获取 $this 属性,

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

要获取$this方法,

$row = $article->getRow();

要获取$this方法的数据,

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

这样可以正常工作,但是如果我想制作/移动下面的这个 dat**a 到 **class 的属性

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

所以我可以像这样调用数据,

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

有可能吗?

【问题讨论】:

    标签: php class oop properties


    【解决方案1】:

    您需要使用神奇的__set() 方法来创建不存在的属性。然后将对象返回从方法移动到简单的属性分配

    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
    

    如果你想保存你当前的逻辑(你说移动,但可以肯定的是,你不想破坏你的 getRow() 逻辑),你可以在另一个方法(或构造函数)中移动分配。

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

    此外,如果您不想神奇地使用来自getRow() 的属性,您可以在__set() 方法中取消设置任何其他分配:

    $rows = (array)$this->getRow();
    if (!array_key_exists($name, $rows)) {
        unset($this->$name);
    }
    

    【讨论】:

      【解决方案2】:

      一种可能的方法是像这样设置这个属性:

      class article
      {
          public function __construct() 
          {
              $array = array(
                  "article_id" => 1,
                  "url"       => "home",
                  "title"     => "Home",
                  "content"   => "bla bla"
              );
           foreach($array as $key => $value){
              $this->{$key} = $value;
            }
         }
      }
      

      现在你可以得到:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-14
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 1970-01-01
        • 2020-03-11
        • 1970-01-01
        相关资源
        最近更新 更多