How to access static properties in an object in PHP

1 Answer

0 votes
class Configuration {
    // Define a static property with visibility control (private/protected/public)
    private static string $environment = "production";

    // A static method to access the private static property from within the class
    public static function getEnvironment(): string {
        // Use 'self::' to access static properties from inside class methods
        return self::$environment;
    }

    // A static method to modify the static property
    public static function setEnvironment(string $newEnv): void {
        self::$environment = $newEnv;
    }
}

// --- Example Usage ---

// 1. Accessing via a public static getter method
echo "Current Environment: " . Configuration::getEnvironment() . "\n";

// 2. Modifying via a public static setter method
Configuration::setEnvironment("staging");
echo "Updated Environment: " . Configuration::getEnvironment() . "\n";

/* 
 * Note on Public Static Properties:
 * If a static property is declared as 'public', you can access it directly 
 * from outside the class using ClassName::$propertyName:
 * 
 * class PublicConfig {
 *     public static string $appName = "MyService";
 * }
 * echo PublicConfig::$appName;
 */


/*
run:

Current Environment: production
Updated Environment: staging

*/

 



answered Oct 30 by avibootz
...