How to make your PHP class

Build a PHP class w/ an example: Learn how to create your own custom class & use it in PHP w/ an easy to follow example.

Creating a Simple PHP Class

Creating a basic PHP class is a straightforward process. The following example creates a class called MyClass with two properties and one method. The MyClass class also contains a constructor, which allows us to initialize the class with certain values when it's first created.

<?php

class MyClass {
  // Properties
  public $prop1 = "I'm a class property!";
  public $prop2 = "I'm an another class property!";

  // Method
  public function myMethod() {
    echo "I'm a class method!";
  }

  // Constructor
  public function __construct() {
    echo "MyClass Object Initiated!<br />";
  }
}

// Create an instance of the class
$myclass = new MyClass;

// Call a method
$myclass->myMethod();

// Get a property
echo $myclass->prop1;

?>

In the above example, the MyClass class has two public properties, $prop1 and $prop2, which can be accessed from outside the class. The class also contains a method called myMethod(), which can be invoked to perform an action. Lastly, the class contains a constructor, which allows us to initialize the class with certain values when it's first created.

In order to use the MyClass class, we need to create an instance of it. This is done using the new keyword. Once the instance is created, we can access the class's properties and methods using the $myclass instance. For example, we can call the myMethod() method by using $myclass->myMethod() and we can access the $prop1 property by using $myclass->prop1.

When the above code is run, it will output the following:

MyClass Object Initiated!
I'm a class method!
I'm a class property!

The code first creates an instance of the MyClass class. The constructor is then called, which outputs the message "MyClass Object Initiated!". After that, the myMethod() method is called, which outputs the message "I'm a class method!". Finally, the value of the $prop1 property is printed, which outputs the message "I'm a class property!".

Answers (0)