Reputation: 2229
Can somebody explain to me the concept of object scope in PHP? I'm very new to objects in PHP and the reason I ask is because I was able to create an object within an if statement, and then access the object outside the scope of the if statement.
Example:
//only create object if some condition is met
if ($conditionTrue){
$myBook = new Book('PHP for Dummies','softcopy');
}
$myBook.read();
I would have though that this would generate an error but it didn't.
Some background to my question
I was trying to figure out how to determine which constructor to call depending on the condition that is met. The only conceivable way was to introduce an if statement
but doing that, I thought would impose the issue of scope
which it didn't and I'm just wondering why..
Upvotes: 2
Views: 1980
Reputation: 30488
This scenario will generate error in other languages like JAVA,C#
. But in PHP
this is not going to happen.
Because in PHP
we can create variable anywhere there is no need to first initialise the variable and after that assign the values in it.
In this scenario when you assigns the value to $myBook
it first initialises the variable $myBook
for global scope. So when you accessing the $myBook
outside if
block, it is already present in global scope of document and because of that you can access it without generating eror.
The above scenario has some limitation like where the variable is initialised, eg (within function, within class).
Upvotes: 1
Reputation: 11830
In PHP, if doesn't have its own scope. So yes, if you define something inside the if statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if statement gets to run).For more about the PHP scope, read the variable scope manual page.
Upvotes: 1