与多个PHP类交互

时间:2016-03-28 17:25:05

标签: php wordpress

我正在学习PHP课程。我可以编写一个基本的PHP类,但在从其他类访问变量和函数时遇到麻烦 我的第一堂课

Class First_class
{
  public $options;
  function __construct() 
   { 
      $this->options = get_option('theme_options'); //wordpress fn
   }
  function my_function() {
    add_menu_page(...)
  }
}

Class Second_class
{
 public $first_class_object;
function __construct() 
   { 
      $this->first_class_object = new First_class();
      //Trying to access $this->options here
   }
}

new Second_class();
Class Third_class
{
 public $first_class_object;
function __construct() 
   { 
      $this->first_class_object = new First_class();
      //Trying to access $this->options here
   }
}
 new Third_class();

我试图在第二类和第三类中使用$first_class_object = new First_class();从类First_class访问公共变量。你看到我在其他类add_menu_page()中启动新的First Class时会触发两次。我不确定如何正确访问变量和函数。可能是建设者? 对不起,我可能有点不对劲吗?

我正在寻找专家建议。

3 个答案:

答案 0 :(得分:1)

扩展你的课程。

以下使用您的代码作为示例。 3v4l demo is herephp extends docs are here

<?php 

class FirstClass 
{
    public $options;

    public function __construct() 
    { 
        $this->options = ['yay']; //get_option('theme_options'); //wordpress fn
    }

    public function myFunction() 
    {
        //
    }
}

class SecondClass extends FirstClass
{

}

class ThirdClass extends FirstClass
{

}

$secondClass = new SecondClass();
var_dump($secondClass->options);

$thirdClass = new ThirdClass();
var_dump($thirdClass->options);

答案 1 :(得分:-1)

尝试扩展类

class Third_class extends First_class
{
   public $first_class_object;

   function __construct() 
   { 
      $this->first_class_object = new First_class();
      //Trying to access $this->options here
   }
}

或使用此构造访问您的课程

$this->first_class_object->option

答案 2 :(得分:-1)

如果您尝试访问其他类属性,则可以使用className::propertyName

如果您想访问班级中的媒体资源,可以使用self::$this

了解有关在类下访问属性和遍历的更多信息。

http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php