PHP | var keyword
Last Updated :
26 May, 2021
The var keyword in PHP is used to declare a property or variable of class which is public by default. The var keyword is same as public when declaring variables or property of a class.
Note: The var keyword was deprecated from version 5.0.0 up to version 5.1.2. Since PHP 5.1.3 it has been added again.
Syntax:
class className {
var $variable = "GeeksforGeeks";
// Other statements
}
Below programs illustrate the var keyword in PHP:
Program 1: This program illustrates the var keyword.
php
<?php
class Geeks {
var $var1 = 'Public' ;
protected $var2 = 'Protected' ;
private $var3 = 'Private' ;
}
$obj = new Geeks();
echo $obj ->var1 . "\n" ;;
?>
|
Output:
Public
Program 2: This program illustrates the var and public keyword.
php
<?php
class Geeks {
var $var1 = 'Var Public' ;
public $var2 = 'Public' ;
}
$obj = new Geeks();
echo $obj ->var1 . "\n" ;
echo $obj ->var2 . "\n" ;;
?>
|
Output:
Var Public
Public
Program 3: This program demonstrating the error while calling private variables.
php
<?php
class Geeks{
var $var1 = 'Var Public' ;
private $var2 = 'Private' ;
}
$obj = new Geeks();
echo $obj ->var1 . "\n" ;;
echo $obj ->var2 . "\n" ;;
?>
|
Output:
Var Public
Error:
PHP Fatal error: Uncaught Error: Cannot access private property
Geeks::$var2 in /home/46488c166fd1197d687867f62e03b8b8.php:24
Stack trace:
#0 {main}
thrown in /home/46488c166fd1197d687867f62e03b8b8.php on line 24
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...