How do I Instantiate a class within a class in .php

前端 未结 3 1428
花落未央
花落未央 2021-01-27 10:56

I\'m new to OOP and I can\'t figure out why this isn\'t working. Is it not ok to instantiate a class with in a class. I\'ve tried this with included file with in the method an

3条回答
  •  Happy的楠姐
    2021-01-27 11:20

    Are you saying that you want to access $go? because, if that is the case, you need to change the scope of it.

    As you see, $go in this method is only available inside activate():

    private function activate() {
        $go = new Activate('Approved');
    }
    

    to make it reachable from other location within the class, you would need to declare it outside activate():

    private $go = null;
    

    you call $go by using $this:

    private function activate() {
        $this->go = new Activate('Approved');
    }
    

    After that, if you want to access go from outside class, you would need to create wrapper:

    public function getGo(){
       return $this->go;
    }
    

    Hope this helped. Also, you can read the documentation about OOP in PHP.

提交回复
热议问题