Ora

How to Make a Variable Public in PHP?

Published in PHP Variable Scope 4 mins read

In PHP, the term "public" for a variable can refer to two distinct concepts: making a variable globally accessible throughout your script, or defining a public property within a class. Understanding both is crucial for managing variable scope and visibility effectively.

1. Making a Variable Globally Accessible (Global Scope)

When you want a variable to be accessible and modifiable from anywhere in your PHP script—including inside functions and across different files—you are dealing with global scope. A variable declared this way is often what people mean by "public" outside of an object-oriented programming (OOP) context.

To achieve this, PHP provides two primary mechanisms: the global keyword and the $_GLOBALS superglobal array.

Using the global Keyword

A global variable is a variable that can be accessed and modified from anywhere in the PHP script. To make an existing variable available within a function or a specific code block, you must explicitly declare it as global inside that scope.

Syntax:

<?php
$myGlobalVar = "Hello World"; // Declared in global scope

function accessGlobalVariable() {
    global $myGlobalVar; // Declare $myGlobalVar as global inside the function
    echo $myGlobalVar; // Output: Hello World
    $myGlobalVar = "Updated Value"; // Modify the global variable
}

accessGlobalVariable();
echo "<br>" . $myGlobalVar; // Output: Updated Value
?>

Key Points:

  • Explicit Declaration: You must use the global keyword inside the function or code block where you intend to use the globally-scoped variable.
  • Modification: Changes made to a global variable within a function using global will affect its value everywhere else in the script.
  • Readability: Overuse of global can make code harder to read, debug, and maintain, as it creates implicit dependencies.

Using the $_GLOBALS Superglobal Array

PHP provides a built-in superglobal array called $_GLOBALS (note the plural 'S') that stores all global variables. This array is automatically available in every scope, eliminating the need for the global keyword. The variable name acts as the key in this associative array.

Syntax:

<?php
$anotherGlobalVar = "PHP is fun!"; // Declared in global scope

function accessGlobalViaSuperglobal() {
    echo $_GLOBALS['anotherGlobalVar']; // Access directly
    $_GLOBALS['anotherGlobalVar'] = "PHP is powerful!"; // Modify directly
}

accessGlobalViaSuperglobal();
echo "<br>" . $anotherGlobalVar; // Output: PHP is powerful!
?>

Key Points:

  • Automatic Availability: $_GLOBALS is accessible from any scope without explicit declaration.
  • Associative Array: Variables are accessed using their names as string keys (e.g., $_GLOBALS['variableName']).
  • Performance: There can be a slight performance overhead when using $_GLOBALS compared to global for frequent access, though it's often negligible in typical applications.
  • Best Practice: While effective, relying heavily on $_GLOBALS can also lead to less maintainable code due to widespread dependencies.

When to Use Global Variables

  • Configuration Settings: Storing application-wide configuration that rarely changes.
  • Database Connections: Managing a single database connection object for the entire application (though often better handled with dependency injection or singletons).
  • Simple Scripts: For small, non-OOP scripts where passing variables through function parameters would be overly cumbersome.

2. Making a Class Property Public (OOP Context)

In Object-Oriented Programming (OOP) with PHP, "public" is an access modifier that defines the visibility of properties (variables) and methods within a class. A public property means it can be accessed and modified directly from outside the class instance.

Using the public Access Modifier

To make a property "public" in a class, you prepend its declaration with the public keyword.

Syntax:

<?php
class Product {
    public $name; // A public property
    public $price; // Another public property

    private $sku; // A private property, not publicly accessible

    public function __construct($name, $price, $sku) {
        $this->name = $name;
        $this->price = $price;
        $this->sku = $sku;
    }

    public function getProductDetails() {
        return "Product: " . $this->name . ", Price: $" . $this->price;
    }
}

$laptop = new Product("Gaming Laptop", 1500, "GL-456");

// Accessing and modifying public properties directly
echo $laptop->name; // Output: Gaming Laptop
$laptop->price = 1450;
echo "<br>" . $laptop->getProductDetails(); // Output: Product: Gaming Laptop, Price: $1450

// Attempting to access a private property directly would cause an error:
// echo $laptop->sku; // Fatal error: Uncaught Error: Cannot access private property Product::$sku
?>

Key Points:

  • Encapsulation: While public provides direct access, it often violates the principle of encapsulation, where internal data should be protected. It's generally preferred to access and modify properties via public methods (getters and setters).
  • Direct Access: public properties can be read and written to directly using the object operator (->).
  • Other Modifiers: PHP also has protected (accessible within the class and its subclasses) and private (accessible only within the class itself) access modifiers.

When to Use Public Class Properties

  • Data Transfer Objects (DTOs): For simple objects primarily used to hold and transfer data, where direct access doesn't pose significant risks.
  • Configuration Objects: For objects holding configuration settings that are meant to be widely readable.
  • Simplicity over Strict Encapsulation: In scenarios where the overhead of getters and setters is deemed unnecessary for very straightforward data.

Comparison of Global Variables and Public Class Properties

Feature Global Variables (global / $_GLOBALS) Public Class Properties (public keyword)
Scope Accessible throughout the entire script. Accessible from outside the class instance.
Context Procedural or non-OOP code blocks. Object-Oriented Programming (within a class).
Access Method global $var; or $_GLOBALS['var']; $object->property;
Encapsulation None; direct exposure across the script. Low; direct exposure from outside the class.
Best Practice Generally discouraged for complex applications due to high coupling. Use with caution; prefer getters/setters for better control.
Primary Purpose Sharing data across different functions/parts of a script. Defining attributes of an object that are meant to be exposed.

Conclusion

The choice between using global variables and public class properties depends entirely on your architectural needs. For non-OOP contexts, global variables offer a way to make data widely accessible. In OOP, public class properties define the external interface of an object. For robust and maintainable applications, it's often recommended to minimize the use of both, favoring dependency injection, parameter passing, and proper encapsulation (using private/protected properties with public getters/setters) to manage data flow.