PHP - 将对象传递到另一个类的最佳实践?

时间:2015-04-23 15:38:25

标签: php

假设我有以下课程:AttributesQuote

    class Attributes {
         private $attr1; 

         public function __construct($attr)
         {
              // implementation 
         }

   }

   class Quote {
       private $obj;

       public function __construct($id, $obj)
       {
           $this->obj = $obj;  
           var_dump($this->obj); 
       }
   }

因此,我可以以某种方式将对象传递给Quote的构造函数,如下所示:

$attr = new Attributes("1");
$quote = new Quote(1, $attr);

这样做,只给我一个空白页?

2 个答案:

答案 0 :(得分:1)

它不起作用,因为您正在尝试直接访问变量。您可以将变量设置为public,也可以在Attributes类中编写get函数。

你在完整的例子中也犯了输入错误;)

答案 1 :(得分:0)

有关private,protected和public之间差异的详细信息,请参阅 PHP:可见性: http://php.net/manual/en/language.oop5.visibility.php

这是你的代码:

<?php
    session_start();

    class Attributes {

        public $intro;
        protected $column1;
        protected $column2;
        protected $cost;
        protected $dateValid;
        protected $TAC;

        public function __construct($theIntro, $theColumn, $theColumn2, $theCost, $theDateValid, $theTAC)
        {
            $this->intro   = $theIntro;
            $this->column1 = $theColumn;
            $this->column2 = $theColumn2;
            $this->cost    = $theCost;
            $this->dateValid = $theDateValid;
            $this->TAC = $theTAC;
        }
    }

    class Quote {

        private $QuoteID;
        private $attr;

        public function __construct($id, $obj)
        {
            $this->attr = $obj;
            $this->QuoteID = $id;

            echo $this->attr->intro; 

            var_dump($this->attr->intro);
        }



    }


$attr = new Attributes("1", "2", "3", "4", "5", "6");
$quote = new Quote("1", $attr); 
?>