Julius Posted March 14, 2012 Share Posted March 14, 2012 Hi, I'm trying to write myself a tiny MVC framework and having some trouble: <?php class One { public function main ( ) { $var = 'Hello'; include ( 'file.php' ); } } ?> file.php: <?php echo $var; ?> This doesn't work. Is there any way without setting that variable to global, to reach it like that? Quote Link to comment https://forums.phpfreaks.com/topic/258886-classes-and-included-files/ Share on other sites More sharing options...
requinix Posted March 14, 2012 Share Posted March 14, 2012 You did remember to instantiate the class and call the function, right? $one = new One(); $one->main(); Quote Link to comment https://forums.phpfreaks.com/topic/258886-classes-and-included-files/#findComment-1327143 Share on other sites More sharing options...
Julius Posted March 14, 2012 Author Share Posted March 14, 2012 I guess you didn't understand my problem. Yes, I did run that method. It gives me an error because of that variable (not defined). How can I reach it? I know that in codeigniter's view file you can just type echo $this -> var; or something like that, and the variable value is shown Quote Link to comment https://forums.phpfreaks.com/topic/258886-classes-and-included-files/#findComment-1327154 Share on other sites More sharing options...
cpd Posted March 14, 2012 Share Posted March 14, 2012 I guess you didn't understand my problem. Yes, I did run that method. It gives me an error because of that variable (not defined). How can I reach it? I know that in codeigniter's view file you can just type echo $this -> var; or something like that, and the variable value is shown You've created an internal method variable (can't remember the exact name, help anyone?) which can only be accessed inside that method therefore you do not need to use $this. Instead you just echo the variable name. See below for the correct way to use $this. class Foo { public $external = "My external method var."; public function Bar(){ $internal = "My internal method var."; echo "{$this->external} {$internal}"; } } $class = new Foo; $class->Bar(); // Displays "My extenal method var. My internal method var" echo $class->external // Displays "My extenal method var." Quote Link to comment https://forums.phpfreaks.com/topic/258886-classes-and-included-files/#findComment-1327156 Share on other sites More sharing options...
trq Posted March 14, 2012 Share Posted March 14, 2012 The code you have posted works fine for me. Quote Link to comment https://forums.phpfreaks.com/topic/258886-classes-and-included-files/#findComment-1327163 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.