in this article I will show you how to create classes
in php. I know that the topic is not part of this course but I am reading a book related to php programming lenguage and I consider this so useful.
What is a class?
If you do not know what a class is, don’t worry, I will tell you. A class is a kind of template for the objects, because if you do not know, php is a object-oriented lenguage. So, the class is as a template and the instances are the objects. Every objects has attributes and methods. I will show you and quick example:
<?php
class Brand{
private $name;
function setName($name){
$this -> name = $name;
}
function getName(){
return $this -> name;
}
}
$SpaceX = new Brand();
$SpaceX -> setName("Tesla");
print "Name = ".$SpaceX -> getName()."\n";
?>
In this example it is important to keep in mind that we are doing a class named Brand
and we created two methods (traditionally named functions) and the we assign the respective values and we print the information we want to watch. The result of this code is the following:
Name = Tesla
But we can do more than that, we can add as many variables or attributes as we want. For example, if we want to add the founders of the brand and the business of the brands we can code the following:
<?php
class Brand{
private $name;
private $founder;
private $business;
function setName($name){
$this -> name = $name;
}
function getName(){
return $this -> name;
}
function setFounder($founder){
$this -> founder = $founder;
}
function getFounder(){
return $this -> founder;
}
function setBusiness($business){
$this -> business = $business;
}
function getBusiness(){
return $this -> business;
}
}
$SpaceX = new Brand();
$SpaceX -> setName("Tesla");
$SpaceX -> setFounder("Elon Musk");
$SpaceX -> setBusiness("Space industry");
print "Name = ".$SpaceX -> getName()."\n\t\t";
print "Founder = ".$SpaceX -> getFounder()."\n\t\t";
print "Business = ".$SpaceX -> getBusiness()."\n";
?>
And the result is the following:
Name = Tesla
Founder = Elon Musk
Business = Space industry
Practice on your own and let me know in the comments
a