PHP Properties

Yo Yogesh.M Updated 17 Oct 2026
6 min read ·Lesson 57 of 248
In this post

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

PartExamplePurpose
Visibilitypublic, private, protectedWho may read and write the property (see PHP Access Modifiers)
Typestring, float, ?string, array, ProductWhich values are allowed
Name$priceDeclared with $, accessed without: $product->price
Default= 0.0Initial 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 TypeError at the moment of assignment — the property never holds invalid data.
  • With declare(strict_types=1);, even '99.5' is rejected (only int → float widening 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 $phone is uninitialized — not null — 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

  • stdClass objects (for example, from json_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)
FunctionAnswers
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

  1. Required fields (name, email) default to empty strings; optional fields default to null.
  2. completeness() counts filled fields: 3 of 5 = 60%.
  3. 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 null defaults 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else User-defined Functions Slicing Strings Function Arguments PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators AJAX PHP AJAX Database AJAX XML AJAX Live Search AJAX Poll AJAX with JSON Security Introduction Password Hashing SQL Injection Prevention XSS Prevention Garbage Collection Project: Simple Blog PHP What is OOP PHP Classes/Objects The $this Keyword Access Array Items Update Array Items Add Array Items Remove Array Items Sorting Arrays Multidimensional Arrays Array Destructuring Array Spread Operator Search in Arrays Merge Arrays PHP Abstract Classes PHP Interfaces Polymorphism PHP Traits PHP Static Methods PHP Static Properties Late Static Binding Magic Methods Object Cloning MySQL Database MySQL Connect MySQL Create DB MySQL Create Table MySQL Insert Data MySQL Get Last ID MySQL Insert Multiple MySQL Prepared MySQL Select Data MySQL Where Debugging PHP Project: Image Upload Gallery $_SESSION $_ENV PHP RegEx RegEx Patterns Heredoc and Nowdoc RegEx Modifiers preg_match preg_replace preg_split PHP RegEx Functions Nullable Types Mixed and Never Types Nullsafe Operator PHP Attributes PHP Fibers Readonly Classes Property Hooks (PHP 8.4) Asymmetric Visibility (PHP 8.4) Reflection API SPL Data Structures Composer PHP Form Handling PDO Transactions PDO Error Handling PHP XML Parsers PHP SimpleXML Parser PHP SimpleXML - Get PHP XML Expat Parser PHP DOM Parser PHP XMLReader PHP XMLWriter AJAX Intro PHP Class Constants Encryption with Sodium Recursive Functions Variable Functions Anonymous Functions Closures Arrow Functions First-class Callable Syntax PHP Arrays Indexed Arrays Associative Arrays Create Arrays Variables Scope Static Variables Variable Variables PHP Echo / Print PHP printf / sprintf PHP Data Types PHP Booleans PHP NULL PHP Strings String Functions array_map / array_filter / array_reduce Array Functions PHP Superglobals $GLOBALS What Is `$_SERVER` ? $_REQUEST $_POST $_GET $_FILES $_COOKIE PHP Type Juggling MySQL Order By MySQL Delete Data MySQL Update Data MySQL Limit Data MySQL Joins with PHP Pagination with PHP PDO Introduction PDO Connect PDO Prepared Statements PDO Fetch Modes PSR-4 Autoloading Installing Extensions (PECL / PIE) OPcache & Performance PHP-FPM Project: Contact Form with Email Project: Login & Registration System Project: CRUD App with MySQL Project: Shopping Cart with Sessions Project: REST API with PHP DateTime Class Timezones PHP Include Include vs Require PHP File Handling PHP File Open/Read PHP File Create/Write File Delete / Rename / Copy PHP Directories PHP CSV Files
Ask about this post
AI Ask about this post

Ask questions about PHP Properties and get answers drawn from it.

Signed-in readers only.