最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Access variable from another class that was passed in constructor

programmeradmin1浏览0评论

I'm coding a WP plugin using PHP OOP. I'm passing some classes to my main class, so that I will be able to access variables and methods from my main class to other classes. In fact I'm able to access methods, but not variables. For example we have Main and Secondary classes:

class Main {
    public $secondary;

    public function __construct($secondary) {
        $this->secondary= $secondary;
    }

    public function methodFromSecondary() {
        echo $this->secondary->secondaryMethod();
    }

    public function variableFromSecondary() {
        echo $this->secondary->secondaryVariable;
    }
}

class Secondary {
   public $secondaryVariable;

   public function __construct() {
       $this->secondaryVariable = 'some variable string';
   }

   public function secondaryMethod() {
       return 'some mothod string';
   }
}

$secondary = new Secondary();
$main = new Main($secondary);

If I call $main->methodFromSecondary() it outputs 'some mothod string' and if I call $main->variableFromSecondary(), WP outputs that site is experiencing technical issues. So how can I access a variable to output 'some variable string' as I access method?

发布评论

评论列表(0)

  1. 暂无评论