This article describes object-oriented programming (OOP) in PHP. I'll show you how to use object-oriented concepts to make fewer code but better programs. Good luck to all of you.
The concept of object-oriented programming has a different perspective for each author, and I remind you of what an object-oriented language should be:
-Data abstraction and information hiding
-Inherit
-Polymorphism
Ways to encapsulate a class in PHP:
<?php
class Something {
// In OOP classes are usually named starting with a cap letter.
var $x;
function setX($v) {
// Methods start in lowercase then use lowercase to seprate
// words in the method name example getValueOfArea()
$this->x=$v;
}
function getX() {
return $this->x;
}
}
?>
Of course you can use your own method, but there is always a good standard.
The data members of a class in PHP use the "var" definition, and the data members are not typed until they are assigned. A data member may be an integer, an array, a union array (associative array), or even an object. method to define a function in a class, to access data members in a method, you must use a $this->name method, otherwise it is a local variable for a function.
Use new to create an object
$obj = new Something;
Then use the member function
$obj->setx (5);
$see = $obj->getx ();
The SetX member function assigns 5 to the object (instead of the Class) member variable in obj, and then GetX returns the value 5.
You can also use object references to access member variables, such as: $obj->x=6; However, this is not a good object-oriented programming method. I insist. You should use a member function to set the value of a member variable and to read a member variable by using a member function. If you think that member variables are not accessible, in addition to using member functions, you will become a good object-oriented programmer. Unfortunately, PHP itself has no way of declaring that a variable is private, so it allows bad code to exist.
Inheritance in PHP is declared using extend.
<?php
class Another extends Something {
var $y;
function setY($v) {
// Methods start in lowercase then use lowercase to seperate
// words in the method name example getValueOfArea()
$this->y=$v;
}
function getY() {
return $this->y;
}
}
?>