In-class access with self::
Learn to access the class's static members from inside with self::.
In-class access with self::
Inside a class, instead of writing the class name to reach a static member, you can use self::. self represents the class where the code is written. Examples: self::$count or self::increment().
This is safer than hardcoding the class name. If you rename the class, self:: still works. It also signals intent: this class's static member.
Important: with self::$count the $ is present (property access). With self::method() there is no $ (method access).
self:: versus $this
self:: and $this point to different things. $this represents the current instance (object); self:: represents the class where the code is written.
From an instance method you can use both: $this->name for an instance property, self::$count for a static property. From a static method, only self:: works; there is no $this.
Example: in a Counter class, the increment() static method does self::$count++; the getCount() static method does return self::$count. No need to repeat the class name.
Exercise Counter: static property and method with self::
Define a Counter class with a public static int $count = 0 property. Add two static methods: increment(): void does self::$count++; getCount(): int does return self::$count. Call Counter::increment() three times, then write echo Counter::getCount() . "\n".
Show example solution
:$count++ in increment, return self::$count in getCount, call Counter::increment() three times, then echo Counter::getCount() . "\n".
Example solution:
<?php
// Write a Counter class with self::
class Counter {
public static int $count = 0;
public static function increment(): void {
self::$count++;
}
public static function getCount(): int {
return self::$count;
}
}
Counter::increment();
Counter::increment();
Counter::increment();
echo Counter::getCount() . "\n";
Test yourself
-
What is self:: for?
- To access instance variables
- To access the class's static members from inside
- To access subclass members
- To call the constructor
Show answer
To access the class's static members from inside — Correct. self:: reaches the class's own static members from inside.
-
Access a static property with self::
class Counter { public static int $count = 0; public static function increment(): void { ____ } }Show answer
class Counter { public static int $count = 0; public static function increment(): void { self::$count++; } } -
Match the self:: and $this expressions
- self::$count
- Static property access
- self::method()
- Static method call
- $this->name
- Instance property access
- self
- Reference to the class itself