mikedag Posted October 28, 2009 Share Posted October 28, 2009 Hi, I am trying to get a grasp on OOP and am struggling to figure somethings out... Say I have 3 files, class1.php, class2.php and index.php If I call class2 from class1 and then only call class1 in index... is it possible to execute functions from class2 in the index file? example... (this obviously does not work!) class class1 { function __construct () { $class2 = new class2(); } } class class2 extends class1 { function somefunction () { echo "blah"; } } Then in the index file: include 'class1.php'; $class1 = new class1 (); $class1->class2->somefunction(); Quote Link to comment https://forums.phpfreaks.com/topic/179418-calling-class-function-from-another-class/ Share on other sites More sharing options...
Alex Posted October 28, 2009 Share Posted October 28, 2009 Your problem is a scope issue. $class2 isn't a property of class1, it's just a variable who is only available in the scope of class1's constructer. You'd need to do it like this: <?php class class1 { public $class2; public function __construct() { $this->class2 = new class2(); } } class class2 { public function test() { echo 'Hello world!'; } } $class1 = new class1(); $class1->class2->test(); ?> Quote Link to comment https://forums.phpfreaks.com/topic/179418-calling-class-function-from-another-class/#findComment-946665 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.