Jump to content

Variable Scope


TomTees

Recommended Posts

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

 

 

Link to comment
https://forums.phpfreaks.com/topic/218609-variable-scope/
Share on other sites

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.

Link to comment
https://forums.phpfreaks.com/topic/218609-variable-scope/#findComment-1133964
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.