如何在父类中调用变量

时间:2016-05-24 14:57:43

标签: php

你好我想在这里帮忙

我上过这堂课:

 class product 
        {
          var $title;
          var $price; 
          function __construct($title1,$price1)
          {

            $this->title=$title1;
            $this->price=$price1;
          }
          function set_title($newtitle){
            $this->title=$newtitle;
          }
          function get_title() {
            return $this->title;
          }
          function set_price($newprice)
          {
           return  $this->price=$newprice;

          }
          function getProductAtrribute ()
          {

             $x1=$this->title;
             $x2=$this->price;
             $x3=$this->**material**;
             $x4=$this->**size1**;
             return   $allattribute= array("$x1","$x2","x3","x4");
         }
        }

和其他课程:

class furinture extends product
    {
      var $size;
      var $material;  

      function __construct($sizeset,$materialset)
      {
        parent::__construct();

        $this->size=$sizeset;
        $this->material=$materialset;
      }
    function  setsize ($size1,$material1)
    {
        $this->size=$size1;
        $this->material=$material1;
    }

我正在尝试做什么我在类家具中设置大小和材料的值但是从函数获取所有属性我尝试制作全局变量但它不会工作。  注意:$ size和$材料我希望他们像定义

一样定义家具类

2 个答案:

答案 0 :(得分:0)

像这样修改您的产品类,

    class product 
    {
      private $title;
      private $price; 
      private $size;
      private $material;  

      public function setup_product($title1,$price1)
      {
        $this->title=$title1;
        $this->price=$price1;
      }

      public function set_title($newtitle){
        $this->title=$newtitle;
      }

      public function set_material($material){
        $this->material=$material;
      }

      public function set_size($size){
        $this->size=$size;
      }

      public function get_title() {
        return $this->title;
      }

      public function get_price() {
        return $this->price;
      }

      public function set_price($newprice)
      {
       return  $this->price=$newprice;

      }

      public function getProductAtrribute()
      {

         $x1=$this->title;
         $x2=$this->price;
         $x3=$this->material;
         $x4=$this->size;
         return $allattribute= array("$x1","$x2","x3","x4");
     }
    }

修改家具类;

class furinture extends product
{
  public function __construct($sizeset,$materialset,$title1,$price1)
  {
    $this->setup_product($title1,$price1)
    $this->size=$sizeset;
    $this->material=$materialset;
  }
  public function setsize($size1,$material1)
  {
    $this->set_size($size1);
    $this->set_material($material1);
  }

 }

答案 1 :(得分:-1)

对您的属性使用public,private或protected而不是var。 然后你可以从$this->price;等访问它......

或者您可以使用parent :: yourMethod();

来访问它