PHP Creating and using classes and objects

In PHP, classes are used to define objects and their properties and methods. To create a class, use the class keyword followed by the name of the class. The properties and methods of the class are defined inside curly braces {}.

Example:

class Dog {
    public $name;
    public $breed;

    public function bark() {
        echo "Woof!";
    }
}

To create an object of a class, use the new keyword followed by the name of the class.

Example:

$dog1 = new Dog();

You can access the properties and methods of an object using the arrow -> operator.

Example:

$dog1->name = "Fido";
$dog1->breed = "Golden Retriever";
$dog1->bark(); // Outputs "Woof!"

Note that the properties and methods can have different visibility levels: public, protected and private. Public properties and methods can be accessed from anywhere, protected can only be accessed from inside the class and its child classes, and private can only be accessed from inside the class.

Leave a Reply