PHP | var keyword

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declaring a class
class Geeks {
  
    // Using var keyword 
    // to declare Public variable
    var $var1 = 'Public';
      
    // Decalring protected variable
    protected $var2 = 'Protected';
      
    // Decalrng private variable
    private $var3 = 'Private';
}
  
// Creating an object
$obj = new Geeks();
  
// Calling var declared variable
echo $obj->var1 . "\n";;
  
?>

chevron_right


Output:

Public

Program 2: This program illustrates the var and public keyword.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declaring a class
class Geeks {
  
    // Using var keyword 
    // to declare Public variable
    var $var1 = 'Var Public';
      
    // Using public keyword 
    // to declare Public variable
    public $var2 = 'Public';
  
}
  
// Creating an object
$obj = new Geeks();
  
// Calling var declared variable
echo $obj->var1 . "\n";
  
// Calling public declared variable
echo $obj->var2 . "\n";;
  
?>

chevron_right


Output:

Var Public
Public

Program 3: This program demonstrating the error while calling private variables.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Declaring a class
class Geeks{
  
    // Using var keyword 
    // to declare Public variable
    var $var1 = 'Var Public';
      
    // Using private keyword 
    // to declare private variable
    private $var2 = 'Private';
  
}
  
// Creating an object
$obj = new Geeks();
  
// Calling var declared variable
echo $obj->var1 . "\n";;
  
// Calling private declared variable
// It will give error
echo $obj->var2 . "\n";;
  
?>

chevron_right


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


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.