2

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

1
  • 1
    It would help if people atleast tell me why this is a poor question when downvoting..*shakes head* Commented Apr 18, 2013 at 4:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was searching for object scope tats probably why I didn't come across the manual page. Thanks.
No Problem Cheers Coding :)
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.