Open In App

PHP | var keyword

Last Updated : 26 May, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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

// Declaring a class
class Geeks {

    // Using var keyword 
    // to declare Public variable
    var $var1 = 'Public';
    
    // Declaring protected variable
    protected $var2 = 'Protected';
    
    // Declaring private variable
    private $var3 = 'Private';
}

// Creating an object
$obj = new Geeks();

// Calling var declared variable
echo $obj->var1 . "\n";;

?>

Output: 
 

Public


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

php
<?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";;

?>

Output: 
 

Var Public
Public


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

php
<?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";;

?>

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


 


Next Article

Similar Reads