PHP Properties
PHP Properties What Are Properties? In simple terms: Properties are the variables that belong to an object — the data each object carries. A Product object has a name, a price, and a stock level; each
What Are Properties?
In simple terms: Properties are the variables that belong to an object — the data each object carries. A Product object has a name, a price, and a stock level; each product object has its own values for them.
Technically: Properties are declared inside a class with a visibility (public, protected, or private), optionally a type, and optionally a default value. Each object created with new gets its own copy of every non-static property. Properties are accessed with the object operator: $object->propertyName.
Declaring Properties
Syntax
class ClassName
{
visibility ?type $name = defaultValue;
}
Example
<?php
class Product
{
public string $name = '';
public float $price = 0.0;
public int $stock = 0;
public ?string $description = null;
public array $tags = [];
private bool $archived = false;
}
$product = new Product();
$product->name = 'Desk Lamp';
$product->price = 1299;
$product->tags[] = 'lighting';
echo "{$product->name}: ₹{$product->price}, tags: " . implode(', ', $product->tags) . "\n";
var_dump($product->description);
Output
Desk Lamp: ₹1299, tags: lighting
NULL
The Parts of a Declaration
| Part | Example | Purpose |
|---|---|---|
| Visibility | public, private, protected | Who may read and write the property (see PHP Access Modifiers) |
| Type | string, float, ?string, array, Product | Which values are allowed |
| Name | $price | Declared with $, accessed without: $product->price |
| Default | = 0.0 | Initial value; must be a constant expression |
Default values follow the same rules as default argument values: literals, arrays, constants, and (since PHP 8.1) enum cases are allowed; function calls are not. Values that must be computed are set in the constructor (see PHP Constructor).
Typed Properties
Since PHP 7.4, properties can declare types. PHP checks every assignment:
<?php
class Product
{
public float $price = 0.0;
}
$product = new Product();
$product->price = '99.5';
var_dump($product->price);
try {
$product->price = 'expensive';
} catch (TypeError $e) {
echo $e->getMessage() . "\n";
}
Output
float(99.5)
Cannot assign string to property Product::$price of type float
- In the default (coercive) mode, the numeric string
'99.5'is converted to a float. - A value that cannot be converted throws a
TypeErrorat the moment of assignment — the property never holds invalid data. - With
declare(strict_types=1);, even'99.5'is rejected (onlyint→floatwidening is allowed).
Allowed Property Types
Property types can be scalar types, array, object, iterable, mixed, class and interface names (including self and parent), nullable types, and union, intersection, and DNF types. Not allowed are void, never, callable, and static — store callables in a Closure-typed property instead.
Uninitialized Properties
A typed property without a default value starts in an uninitialized state. Reading it before assigning a value is an error:
<?php
class Customer
{
public string $name;
public ?string $phone;
}
$customer = new Customer();
var_dump($customer);
try {
echo $customer->name;
} catch (Error $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
object(Customer)#1 (0) {
["name"]=>
uninitialized(string)
["phone"]=>
uninitialized(?string)
}
Error: Typed property Customer::$name must not be accessed before initialization
Why This Is Useful
- "Uninitialized" is different from
null. Even?string $phoneis uninitialized — notnull— until a value is assigned, unless you write= null. - The error reveals bugs where an object was used before it was completely set up, instead of silently working with empty values.
- The usual solution is to require the values in a constructor, so an object can never exist in an incomplete state.
Untyped properties (public $name;) default to null and never have an uninitialized state. Modern code should declare types on all properties.
Dynamic Properties Are Deprecated
Assigning to a property that was not declared creates a "dynamic property". This was allowed in older PHP versions, but it hides typos:
<?php
class Product
{
public string $color = '';
}
$product = new Product();
$product->colour = 'red'; // typo: "colour" instead of "color"
var_dump($product->color);
Output (PHP 8.2+)
PHP Deprecated: Creation of dynamic property Product::$colour is deprecated in /path/script.php on line 8
string(0) ""
The intended property color was never set; the value went into a new, accidental property. Since PHP 8.2, creating dynamic properties raises a deprecation notice, and future versions are expected to turn it into an error.
When Dynamic Properties Are Still Needed
stdClassobjects (for example, fromjson_decode()) allow dynamic properties without warnings.- Classes can opt in explicitly with the
#[\AllowDynamicProperties]attribute — mainly for legacy code. - Classes implementing the magic methods
__get()and__set()can provide dynamic-looking properties in a controlled way (see Magic Methods).
Checking and Removing Properties
<?php
class Profile
{
public string $name = 'Asha';
public ?string $bio = null;
}
$profile = new Profile();
var_dump(isset($profile->name));
var_dump(isset($profile->bio));
var_dump(property_exists($profile, 'bio'));
var_dump(property_exists(Profile::class, 'website'));
Output
bool(true)
bool(false)
bool(true)
bool(false)
| Function | Answers |
|---|---|
isset($obj->prop) | Is the property accessible, initialized, and not null? |
property_exists($objOrClass, 'prop') | Is the property declared (regardless of its value or visibility)? |
unset($obj->prop) | Removes the value; a typed property becomes uninitialized again |
Variable Property Names
<?php
class Profile
{
public string $name = 'Asha';
public string $city = 'Chennai';
}
$profile = new Profile();
foreach (['name', 'city'] as $field) {
echo "$field: {$profile->$field}\n";
}
Output
name: Asha
city: Chennai
$profile->$field reads the property whose name is stored in $field. Never use this with user-supplied names; restrict field names to an allow-list.
Practical Example: Profile Completeness
<?php
class UserProfile
{
public string $name = '';
public string $email = '';
public ?string $phone = null;
public ?string $city = null;
public ?string $bio = null;
public function completeness(): int
{
$fields = [$this->name, $this->email, $this->phone, $this->city, $this->bio];
$filled = count(array_filter($fields, fn(?string $value): bool => $value !== null && trim($value) !== ''));
return (int) round($filled / count($fields) * 100);
}
public function missingFields(): array
{
$missing = [];
foreach (['phone', 'city', 'bio'] as $field) {
if ($this->$field === null || trim($this->$field) === '') {
$missing[] = $field;
}
}
return $missing;
}
}
$profile = new UserProfile();
$profile->name = 'Asha';
$profile->email = 'asha@example.com';
$profile->city = 'Madurai';
echo "Profile {$profile->completeness()}% complete\n";
echo "Add: " . implode(', ', $profile->missingFields()) . "\n";
Output
Profile 60% complete
Add: phone, bio
Step-by-Step Explanation
- Required fields (
name,email) default to empty strings; optional fields default tonull. completeness()counts filled fields: 3 of 5 = 60%.missingFields()checks only the optional fields and uses variable property names over a fixed list.
Common Mistakes
Writing $this->$name Instead of $this->name
Effect: The property name is taken from the variable $name.
Fix: No $ after -> for normal access.
Reading Typed Properties Before Initialization
Effect: Error: Typed property ... must not be accessed before initialization.
Fix: Provide defaults or initialize everything in the constructor.
Relying on Dynamic Properties
Effect: Typos silently create new properties; deprecation notices in PHP 8.2+.
Fix: Declare every property.
Making Everything Public
Effect: Any code can put objects into invalid states.
Fix: Use private properties with methods that enforce rules (see PHP Access Modifiers and Readonly Properties).
Best Practices
- Declare every property with a visibility and a type.
- Use defaults for optional data and constructors for required data.
- Prefer
nulldefaults for genuinely optional values, and empty arrays for lists. - Avoid dynamic properties.
- Keep properties private unless there is a clear reason to expose them.
Official reference: https://www.php.net/manual/en/language.oop5.properties.php