PHP: is it possible to call the nesting method of an object inside a nested object?

I do not know how to explain this better, therefore (see the comment in the second class):

<?php

    class main {
        public function something() {
            echo("do something");
        }
        public function something_else() {
            $child=new child();
            $child->child_function();
        }
    }

    class child {
        public function child_function() {
            echo("child function");
            //is it possible to call main->something() here somehow if this class is initiated inside class main?
        }
    }

?>
+5
source share
4 answers

No. Objects do not just have access to materials in a higher area. You must explicitly pass mainto child:

$child->child_function($this);
+3
source

You have defined the function something_elseas public, so you can access it after creating the object of the main class.

0
source

,   

    class main {
        public function something() {
            echo("do something");
        }
        public function something_else() {
            $child=new child($this);
            $child->child_function();
        }
    }

    class child {
        protected $_main;
        public function __construct($main)
        {$this->_main = $main;}
        public function child_function() {
            echo("child function");
             $this->_main->something();
        }
    }

?>
0

.
, $this- > something(); .

<?php    
    class main {
        public function something() {
            echo("do something");
        }
    }

    class child extends main {
        public function child_function() {
            echo("child function");
            //is it possible to call main->something() here somehow if this class is initiated inside class main?
            $this->something();
        }
    }

?>

__construct() :

public function __construct () {
    parent::__construct();
}

.

0

All Articles