PHP Scope of Variables

One way in which variables in PHP differs from many other languages is the scope in which a variable exists. For someone learning PHP who already knows JavaScript this is one of differences most likely to catch you out.

In JavaScript you can select whether a variable will be global in scope or local to the function it is in by the way you define it. If you define it using the keyword var it is local, otherwise it is global.

PHP doesn't work that way. In PHP all variables are local unless specifically defined as global. While a var keyword does exist in PHP it is optional and has no effect whatever on the scope of the variable. In fact PHP does have three other keywords that can be used when defining variables that do affect the scope of the variable and these are private, protected and public. Specifying var or not specifying any of these keywords is equivalent to specifying public.

Variables (properties) defined as public can be referenced from outside of the object that created them but only by making reference to the property within the object (eg. by using dot notation - Those defined as protected can be referenced from classes that inherit from the class containing them but cannot be accessed from anywhere else. Those defined as private are only accssible to objects where they belong to that class.

So the keyword defines whether the property is accessible from outside the object (in JavaScript all properties are since JavaScript doesn't have classes to need the other two).

JavaScript allows access the other way too with a function or class being able to access global variables as long as it doesn't have a local variable defined with the same name (and even then it can access it by qualifying the name appropriately). PHP doesn't have the same concept of global variables because in PHP a variable defined outside of any functions is not automatically accessible to any function that might decide to reference it. In PHP a function can only access those specific global variables that you specify it should be allowed to access and you do that using the global keyword to define inside the function which global variables that the function can access. Any 'global' variables that you do not define as global inside of a function will not be able to be accessed by that function regardless of whether a local variable with the same name exists or not.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow