4

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?
        }
    }

?>
2
  • Yes, you can pass $this (inside main) to the constructor of child. Be careful you don't end up with spaghetti, though! Commented Sep 20, 2012 at 9:00
  • Thanks deceze and Mihai, I've used your advice and it works just fine. Commented Sep 20, 2012 at 9:17

4 Answers 4

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

?>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.