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

不羁的心 提交于 2021-02-17 05:29:07

问题


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 and it didn't make a change.

include('Activate.php');

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

$run = new First();

回答1:


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.




回答2:


Okay I figured out my issue. My code had two errors. One that being my method was set to private and secondly I had an error in my $parms that I was sending to the class.

include('Activate.php');

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

$run = new First();



回答3:


You can access your private method with the help of create another public function in the same class and call the private function in the public method or function. Now you can call your private function with the help of $run instance.

For example:

class Cars{

function getting(){
    echo ("Hello World");   
}

private function getting2(){
    echo ("Hello World Againg");
}

public function getting3(){
    $this->getting2();
}

}

$class_object=new Cars;

print($class_object->getting3());


Your output screen like the below image.




来源:https://stackoverflow.com/questions/13372556/how-do-i-instantiate-a-class-within-a-class-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!