🐶
PHP

PHP var Keyword Explained: Usage and Alternatives

By Filip on 10/06/2024

Learn about the deprecated PHP 'var' keyword, its historical usage, and why it's no longer recommended in modern PHP development.

PHP var Keyword Explained: Usage and Alternatives

Table of Contents

Introduction

In this article, we'll explore the history and usage of the "var" keyword in PHP. We'll see how it was used in early PHP versions, how its role evolved with the introduction of visibility keywords, and why it's no longer recommended or even valid in modern PHP code. We'll cover its transition to an alias for "public," the reasons behind its deprecation, and the importance of using explicit visibility keywords for better code clarity and compatibility.

Step-by-Step Guide

In the world of PHP, the keyword "var" has a specific history and usage. Let's break it down:

  1. Early Days (PHP 4): Back in PHP 4, "var" was the way to declare variables inside a class. It essentially meant the variable was part of that class's blueprint.

  2. Evolution (PHP 5 and beyond): PHP 5 brought significant improvements to how the language handled objects (the building blocks of object-oriented programming). A key change was introducing visibility keywords:

    • public: A variable declared with "public" is accessible from anywhere – inside the class, from code outside the class, and even by child classes that inherit from it.
    • protected: This limits access to within the class itself and any child classes.
    • private: The most restrictive, "private" variables can only be accessed from within the class where they're defined.
  3. "var" Becomes an Alias: Instead of removing "var" entirely, PHP 5 made it an alias for "public." This meant that code written with "var" would still work, ensuring backward compatibility with older PHP 4 code.

  4. The Push for Clarity: While "var" continued to function, using explicit visibility keywords ("public," "protected," "private") became the recommended practice. This shift promoted clearer, more understandable code, especially as projects grew larger.

  5. Deprecation and Removal: To encourage modern coding practices, PHP 7.1 marked "var" as deprecated. This meant using it would trigger a warning, signaling that it might be removed in future PHP versions. Finally, PHP 8 removed "var" altogether.

In essence:

  • "var" is a relic from older PHP versions.
  • It's functionally the same as "public" when declaring class variables.
  • You should avoid using "var" in modern PHP code. Stick to "public," "protected," or "private" for clarity and to prevent compatibility issues with newer PHP versions.

Code Example

The code demonstrates object-oriented programming in PHP, showcasing both older (PHP 4) and modern (PHP 5+) class syntax and the concept of visibility (public, protected). It defines classes for products, including a discounted product subclass, to illustrate how visibility controls access to properties and methods within and outside of classes and their inheritance chains.

<?php

// PHP 4 style (still works in later versions, but not recommended)
class OldProduct {
  var $name = "Default Product"; 
  var $price = 100;

  function displayInfo() {
    echo "Name: " . $this->name . ", Price: $" . $this->price;
  }
}

$product4 = new OldProduct();
$product4->displayInfo(); // Outputs: Name: Default Product, Price: $100

// PHP 5+ style with visibility keywords (recommended)
class Product {
  public $name = "Default Product";
  protected $price = 100; 

  public function displayInfo() {
    echo "Name: " . $this->name . ", Price: $" . $this->getPrice();
  }

  protected function getPrice() {
    return $this->price;
  }
}

$product5 = new Product();
$product5->displayInfo(); // Outputs: Name: Default Product, Price: $100

// Accessing protected property directly outside the class would cause an error
// echo $product5->price; // Fatal error

// Demonstrating inheritance
class DiscountedProduct extends Product {
  public function applyDiscount($percentage) {
    // Can access protected property from parent class
    $this->price = $this->price - ($this->price * $percentage / 100); 
  }
}

$discountedProduct = new DiscountedProduct();
$discountedProduct->applyDiscount(10); 
$discountedProduct->displayInfo(); // Outputs: Name: Default Product, Price: $90

?>

Explanation:

  • OldProduct class: This demonstrates how "var" was used in PHP 4. Both $name and $price are implicitly public.
  • Product class: This shows the modern approach using visibility keywords. $name is public, $price is protected, and getPrice() provides controlled access to the protected $price.
  • DiscountedProduct class: This illustrates how protected members are accessible within child classes, highlighting the importance of visibility control.

Key Takeaways:

  • Always use public, protected, or private for declaring class properties in modern PHP.
  • Avoid using "var" as it's deprecated and removed in PHP 8.
  • Explicit visibility keywords make your code more readable, maintainable, and less prone to errors, especially in larger projects.

Additional Notes

  • Backward Compatibility: The decision to make "var" an alias for "public" in PHP 5 was crucial for maintaining backward compatibility. This ensured that older PHP 4 code could transition to PHP 5 without immediately breaking. This approach allowed developers to update their codebases gradually.

  • Impact of "var" on Code Readability: Using "var" might seem convenient for brevity, but it harms code readability, especially for developers unfamiliar with older PHP conventions. Explicit visibility keywords make it instantly clear how a variable can be accessed and used.

  • Modern PHP Development: In modern PHP development, adhering to best practices is essential. This includes using explicit visibility keywords, leveraging newer language features, and writing clean, maintainable code.

  • PHP's Evolution and Learning: The journey of the "var" keyword in PHP provides a valuable lesson in how programming languages evolve. It highlights the balance between maintaining backward compatibility and embracing improvements for better code structure and clarity.

  • Importance of Staying Updated: The deprecation and removal of "var" emphasize the importance of staying updated with PHP's latest versions and best practices. Regularly checking for deprecated features and migrating code accordingly ensures long-term codebase health and compatibility.

Summary

PHP Version Usage Visibility Equivalent Recommendation
PHP 4 Required to declare class variables N/A Legacy code only
PHP 5 Becomes an alias for public (backward compatibility) public Use public, protected, or private instead
PHP 7.1 Deprecated (triggers a warning) public Avoid using
PHP 8 Removed N/A Not available, use explicit visibility keywords

Key Takeaways:

  • "var" is outdated and should not be used in modern PHP code.
  • Explicit visibility keywords (public, protected, private) improve code clarity and maintainability.
  • Using "var" can lead to compatibility issues with newer PHP versions.

Conclusion

The "var" keyword in PHP, while once a staple in PHP 4 for declaring class variables, has become obsolete in modern PHP development. With the introduction of visibility keywords ("public," "protected," "private") in PHP 5, "var" was relegated to an alias for "public" and subsequently deprecated in PHP 7.1 before being entirely removed in PHP 8. While "var" provided backward compatibility with older codebases, its use is strongly discouraged in favor of explicit visibility keywords. These keywords not only enhance code readability and maintainability but also align with modern PHP's focus on clarity and best practices. The evolution of "var" serves as a reminder for developers to stay updated with the latest language versions and embrace changes that improve code quality and compatibility. By adhering to these principles, developers can write cleaner, more robust, and future-proof PHP applications.

References

  • PHP var Keyword PHP var Keyword | W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
  • Should I be using the var keyword in PHP? - Stack Overflow Should I be using the var keyword in PHP? - Stack Overflow | Sep 13, 2012 ... PHP4 used var. php4 had objects just like php5, but php5 did a much better job on working with and extending objects. Var is not required by any ...
  • PHP RFC: "var" Deprecation PHP RFC: "var" Deprecation | Mar 10, 2016 ... var is a legacy feature from PHP 4 which has been superseded by the visibility keywords. It was kept in PHP 5+ for backwards-compatibility.
  • Properties - Manual - PHP Properties - Manual - PHP | PHP is a popular general-purpose scripting language that powers everything from your blog to the most popular websites in the world.
  • Drop 'public' not 'var'! Drop 'public' not 'var'! | Mar 26, 2016 ... ... var keyword in PHP 7.1 and remove it in PHP 8. At the time of ... doing, it will take them slightly longer to read the method signatures.
  • Optimization: using the "var" keyword | GameMaker Community Optimization: using the "var" keyword | GameMaker Community | If I understand correctly when you declare a variable using "var" the memory used to store it is then recycled at the end of the event or script. Assuming I understand that correctly; My question is if I need to use a variable every frame but only in the one context, should I use the var keyword...
  • PHP | var keyword - GeeksforGeeks PHP | var keyword - GeeksforGeeks | A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
  • I REFUSE to use "var" : r/csharp I REFUSE to use "var" : r/csharp | Posted by u/fluse1367 - No votes and 21 comments
  • Why do some programming languages declare variables with a ... Why do some programming languages declare variables with a ... | Apr 8, 2020 ... Does PHP have the var keyword? Negative. No var keyword in PHP. To declare a variable in PHP, just precede it with a dollar-sign: $firstName ...

Were You Able to Follow the Instructions?

😍Love it!
😊Yes
😐Meh-gical
😞No
🤮Clickbait