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

前端 未结 3 1401
花落未央
花落未央 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条回答
  • 2021-01-27 11:00

    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.


    0 讨论(0)
  • 2021-01-27 11:19

    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();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题