The object oriented programming concept is great for not only organizing code, but also easing readability. Creating a class in PHP is easy and we will go through the basics. For starters, creating a PHP class is as easy as:
class myFirstClass {
// CLASS CONTENT GOES HERE
}
The next step is to add variables and functions to the class. One of the first functions every class has is a constructor. A constructor is a function that is run when the class object is created. To create a constructor function for your class, a default constructor function name by “__construct()” is used. See the example below
class myFirstClass {
public function __construct() {
// CONSTRUCTOR CONTENT HERE
}
}
Next, you can add variables to your class. Variables can be defined as public or private. Private variables can be accessed only from functions belonging to the class. Public variables on the other hand can be accessed by functions belonging to the class along with functions outside the class. Once we have defined our variables, we can initialize them in our constructor. Below is an expanded example of a public and private variable.
class myFirstClass {
private $myPrivateVariable;
public $myPublicVariable;
public function __construct() {
$this->myPrivateVariable = "Private Message";
$this->myPublicVariable = "Public Message";
}
}
Lastly, we can add functions to our class. Because the $myPrivateVariable is private, we cannot assign it without a custom function. Therefore, in our next example, we will create a function that assigns a string value to the $myPrivateVariable. This function should be public since we want to be able to access it from outside of the class.
class myFirstClass {
private $myPrivateVariable;
public $myPublicVariable;
public function __construct() {
$this->myPrivateVariable = "Private Message";
$this->myPublicVariable = "Public Message";
}
public function assignMyPrivateVariable($message) {
$this->myPrivateVariable = $message;
}
}
Now, we have completed a very basic PHP class. Follow the same steps to create more variables and more functions to make the class more powerful and useful.




