Jump to content

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

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.

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.