Instance vs Static Properties
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 15 of 91.
When you create a property in a class, you need to decide whether it belongs to each individual object or to the class itself. This distinction is the difference between instance properties and static properties.
Instance properties are the default. Each object gets its own copy of the property, and changing it in one object doesn't affect others:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$alice = new User("Alice");
$bob = new User("Bob");
echo $alice->name . "\n";
echo $bob->name . "\n";
Output:
Alice
Bob
Static properties belong to the class, not to any specific object. You declare them with the static keyword and access them using the class name with :: instead of an object with ->:
<?php
class User {
public static $count = 0;
public $name;
public function __construct($name) {
$this->name = $name;
self::$count++;
}
}
$alice = new User("Alice");
$bob = new User("Bob");
echo User::$count;
Output:
2
Notice how $count is shared across all instances. Every time we create a new User, the same $count variable increments. Inside the class, we use self::$count to reference the static property.
Key Point: Use instance properties when each object needs its own value. Use static properties when you need to share data across all objects of a class, like counting instances or storing configuration.
Challenge
EasyLet's build a visitor tracking system that demonstrates the difference between instance properties (unique to each visitor) and static properties (shared across all visitors).
You'll create two files to organize your code:
Visitor.php— Define aVisitorclass that tracks individual visitors and keeps a running count of total visitors. Each visitor should have their own$nameproperty (instance property), while a$totalVisitorsproperty should be shared across all instances (static property). The constructor accepts a name, sets it, and increments the total visitor count. Add agetInfo()method that returns"[name] is visitor #[totalVisitors]".main.php— Include the Visitor class file, then create three visitors with the names"Alice","Bob", and"Charlie"(in that order). After creating all three, print the result of callinggetInfo()on each visitor (each on its own line), then print the total visitor count by accessing the static property directly from the class usingVisitor::$totalVisitors.
Remember that inside the class, you access static properties using self::$propertyName, while from outside the class you use ClassName::$propertyName. Instance properties are accessed with $this->propertyName as usual.
Your output should show each visitor with their assigned number, followed by the final total count on the last line.
Cheat sheet
Instance properties belong to each individual object, while static properties belong to the class itself and are shared across all instances.
Instance Properties:
Each object gets its own copy of the property:
<?php
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$alice = new User("Alice");
$bob = new User("Bob");
echo $alice->name; // Alice
echo $bob->name; // Bob
Static Properties:
Declared with the static keyword and shared across all instances:
<?php
class User {
public static $count = 0;
public $name;
public function __construct($name) {
$this->name = $name;
self::$count++;
}
}
$alice = new User("Alice");
$bob = new User("Bob");
echo User::$count; // 2
Accessing Static Properties:
- Inside the class:
self::$propertyName - Outside the class:
ClassName::$propertyName
Accessing Instance Properties:
- Inside the class:
$this->propertyName - Outside the class:
$object->propertyName
Try it yourself
<?php
// Include the Visitor class
require_once 'Visitor.php';
// TODO: Create three visitors with names "Alice", "Bob", and "Charlie" (in that order)
// TODO: Print the result of getInfo() for each visitor (each on its own line)
// TODO: Print the total visitor count using Visitor::$totalVisitors
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern