How to add a property to a php class?

Member

by daisha , in category: PHP General , a month ago

How to add a property to a php class?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , a month ago

@daisha 

To add a property to a PHP class, you can define it within the class using the public, private, or protected modifiers. Here is an example:

1
2
3
4
5
6
7
class MyClass {
    public $name; // public property
    
    private $age; // private property
    
    protected $address; // protected property
}


In the above example, $name is a public property, which means it can be accessed and modified from outside the class.


$age is a private property, which can only be accessed and modified from within the class itself.


$address is a protected property, which can be accessed and modified from within the class itself and any child classes that inherit from it.


You can then instantiate objects of this class and access the properties like this:

1
2
3
4
5
6
7
8
9
$object = new MyClass();

$object->name = "John"; // Accessing and modifying the public property

echo $object->name; // Accessing the public property

$object->age = 25; // This will throw an error because age is a private property

$object->address = "123 Main St"; // This will throw an error because address is a protected property


Note that private and protected properties cannot be accessed directly from outside the class itself, they can only be accessed through methods defined within the class.