create a class in php

To create a class in PHP, you can use the class keyword followed by the name of your class. Here's a simple example of a class named "Person":

main.php
class Person {
    // properties
    public $name;
    public $age;
    
    // constructor method
    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
    
    // other methods
    public function sayHello() {
        echo "Hello, my name is " . $this->name . ".";
    }
}
330 chars
17 lines

This class has two properties (name and age), a constructor method, and one other method (sayHello). The constructor method is used to initialize the object's properties when it is instantiated.

To instantiate an object of this class, you would use the new keyword, like this:

main.php
$person = new Person("John", 30);
34 chars
2 lines

This creates a new instance of the Person class with the name "John" and age 30. You can then access the object's properties and methods like this:

main.php
echo $person->name; // output: John
$person->sayHello(); // output: Hello, my name is John.
92 chars
3 lines

gistlibby LogSnag