简体   繁体   English

我如何在扩展类中使用主类变量

[英]how can i use main class variable in extendeded class

class a{

$array = array();

}
class b extends a{


**I need to get that array here !**

}

I'm not familiar with oops concept so please somebody help me 我对哎呀概念不熟悉,所以请有人帮我

   class a
   { 

      public $_array = array(); 

   } 

   class b extends a
   { 

      public function getArray()
      {
         return $this->_array;
      }

   } 


   $x = new b();
   echo $x->_array;
   echo $x->getArray();

And read up on visibility in classes , it'll help understand when something is accessible from a child class, or only from the parent 并阅读有关类的可见性 ,它将有助于了解何时可以从子类或仅从父类访问某些内容

You just read property as it would be in child class 您只读了子类中的属性

<?
    class a {
        var $array = array(1,2,3);
    }

    class b extends a {
    }

    $b = new b();
    print_r ($b->array); // prints array
?>

See online . 在线查看。

You need to define your array as public or protected property of your class a 您需要将数组定义为类a的公共或受保护属性

class a {
  protected $array = array();
}

class b extends a {
   public function __construct() {
     $this->array = array('a', 'b', 'c');
   }
}

There are three visibility levels of properties & methods: 属性和方法具有三种可见性级别:

  1. public. 上市。 It means that property is visible outside the class 这意味着该属性在类外部可见
  2. protected. 保护。 This property will be visible in the class and its children (class that extend this one) 该属性将在该类及其子类(扩展该类的类)中可见
  3. private. 私人的。 This property will be visible only from the class where property is defined. 该属性仅在定义了属性的类中可见。

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

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