PHP Class var Function
PHP classes define the objects that deliver the functionality of a website or application. Within class declarations, developers outline the data and behavior of application objects. The var function defines a class variable, which holds an item of data for each object instance of the class. However, the var function is deprecated in recent versions of PHP. Developers can use alternative code constructs or can continue to use var depending on which version of PHP their server is running.
-
Purpose
-
The following sample code demonstrates the var function being used to define a class variable named "helper_type."
<?php
class Helper {
var $helper_type;
}
?>This class declaration outline declares a variable that will be accessible throughout the class. The variable can be assigned a value in more than one location within the class and will be associated with a single object instance of the class, rather than the class as a whole.
Use
-
Developers use the var function to declare class variables, but they must also assign values to these variables. The constructor function of a class often assigns initial values -- or initializes -- class variables as follows.
function Helper() {
$this->helper_type = "admin";
}This code could appear inside the class declaration, after the line declaring the class variable using the var function. When external code creates an object of the class, the content of the constructor function executes, giving the declared variable an initial value. The class could also contain functions in which the value of the variable is altered, as long as the variable is not a constant.
-
Versions
-
In recent versions of PHP, developers are encouraged not to use the var function, although it is still supported for legacy applications. If developers use versions of PHP between 5 and 5.1.3, their code may generate errors if it contains the var function. Versions since then support the function, but interpret it according to the more recent framework for visibility. Variables declared using var are interpreted as having public visibility.
Alternatives
-
For developers using PHP since version 5, the recommended alternative to the var function involves visibility. Visibility indicates the extent to which a particular variable is available to other code. For example, a private variable is only visible within its own class declaration, while a public variable is available outside the class. The following alternative variable declaration demonstrates.
private $helper_type = "admin";
This declares "helper_type" as a variable that is only intended for internal class use and that external code has no access to.
-
References
Resources
- Photo Credit Comstock/Comstock/Getty Images