genericnumber1 Posted November 5, 2006 Share Posted November 5, 2006 Can't seem to get two classes to work together! [b]test.class1.php[/b]:[code]<?phpclass class1 { public function test1(){ echo "worked!"; }}$class1 = new class1;?>[/code][b]test.class2.php[/b]:[code]<?phpclass class2 { public function test2(){ $class1->test1(); }}$class2 = new class2;?>[/code][b]test.php[/b]:[code]<?phprequire_once("test.class1.php");require_once("test.class2.php");$class2->test2();?>[/code]Running "test.php" yields:[b]Fatal error: Call to a member function test() on a non-object in[/b] [i][filepath][/i][b]test.class2.php on line 4[/b]Effects are the same if I define the classes in test.php as well. I'm sure it's a stupid mistake of mine, trying to do something php just doesn't like or something that just plain doesn't work. Link to comment https://forums.phpfreaks.com/topic/26198-interaction-between-unrelated-seperate-filed-classes/ Share on other sites More sharing options...
Zane Posted November 5, 2006 Share Posted November 5, 2006 in order to use a class you have to declare an object of that classi.e.$myObj1 = new class2();$myObj1->test(); Link to comment https://forums.phpfreaks.com/topic/26198-interaction-between-unrelated-seperate-filed-classes/#findComment-119814 Share on other sites More sharing options...
toplay Posted November 5, 2006 Share Posted November 5, 2006 In method test2() you're using $class1 variable. $class1 variable is defined outside class2. PHP doesn't know anything about it. http://php.net/manual/en/language.variables.scope.php[code=php:0]<?phpclass class2 { public function test2(){ $class1 = new class1(); $class1->test1(); }}[/code] Link to comment https://forums.phpfreaks.com/topic/26198-interaction-between-unrelated-seperate-filed-classes/#findComment-119816 Share on other sites More sharing options...
genericnumber1 Posted November 5, 2006 Author Share Posted November 5, 2006 thanks! wasn't thinking about variable scope..[code]<?phpclass class2 { public function test2(){ $GLOBALS['class1']->test(); }}?>[/code]did the trick ;) thanks so much! Link to comment https://forums.phpfreaks.com/topic/26198-interaction-between-unrelated-seperate-filed-classes/#findComment-119818 Share on other sites More sharing options...
Zane Posted November 5, 2006 Share Posted November 5, 2006 oops I completely missed the declarations sry Link to comment https://forums.phpfreaks.com/topic/26198-interaction-between-unrelated-seperate-filed-classes/#findComment-119823 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.