Caballero
Caballero

Reputation: 12101

PHP: is it possible to call nesting object's method inside nested object?

I don't know how to explain this better, so (see comment inside 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?
        }
    }

?>

Upvotes: 4

Views: 468

Answers (4)

Kao
Kao

Reputation: 2272

You can extend your child object with main.
This allows child to access the parent classes by calling $this->something(); as it becomes a member of the main class, and gains access to all of it's properties and methods.

<?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();
        }
    }

?>

if you want to __construct() in both you can do:

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

This goes for all methods.

Upvotes: 0

Tarun
Tarun

Reputation: 3165

try this,

    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();
        }
    }

?>

Upvotes: 0

Riz
Riz

Reputation: 10246

You have defined the function something_else as public, so you can access that after creating object of main class.

Upvotes: 0

deceze
deceze

Reputation: 522024

No. Objects do not simply have access to stuff in a higher scope. You need to pass main into child explicitly:

$child->child_function($this);

Upvotes: 2

Related Questions