TomTees Posted November 14, 2010 Share Posted November 14, 2010 In this code... class Model { public function getBook($title) { $allBooks = $this->getBookList(); return $allBooks[$title]; } } Questions: --------------- 1.) What is the scope of $allBooks? Can it be seen outside the function and inside the class? 2.) Could I rewrite things like this... class Model { protected $allBooks; public function getBook($title) { $allBooks = $this->getBookList(); $this->allBooks = $this->getBookList(); return $allBooks[$title]; } } 3.) Sorta off-topic, but could I rewrite this code... $allBooks = $this->getBookList(); return $allBooks[$title]; like this... return $allBooks = $this->getBookList([$title]); TomTees Quote Link to comment https://forums.phpfreaks.com/topic/218609-variable-scope/ Share on other sites More sharing options...
s0c0 Posted November 14, 2010 Share Posted November 14, 2010 I'm not good with terminology but in your first example the variable $allbooks can only be accessed within that function since it was only defined in that function. To access it outside of the method it would need to be defined as a data attribute of the class Model. So yes, $this->allBooks would be accessible from the object. Quote Link to comment https://forums.phpfreaks.com/topic/218609-variable-scope/#findComment-1133964 Share on other sites More sharing options...
requinix Posted November 14, 2010 Share Posted November 14, 2010 As for the other two, 2) Yes, but the return statement won't work. 3) Yes, but there's no point to using the $allBooks variable in that case. Quote Link to comment https://forums.phpfreaks.com/topic/218609-variable-scope/#findComment-1134010 Share on other sites More sharing options...
ignace Posted November 14, 2010 Share Posted November 14, 2010 return $allBooks = $this->getBookList([$title]); You probably are referring to: return $this->getBookList()[$title]; And no you can't do that in PHP neither can you do: (new Object())->method(); Few things I liked about Java. Quote Link to comment https://forums.phpfreaks.com/topic/218609-variable-scope/#findComment-1134017 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.