Classes & Object are basic concept of oops in PHP (Object Oriented Programming).
Basic concept of class was introduced from php4 which is the main piller of oop but complete features of class is introduced in php5 such as access modifier or interface.
It is very easy to define class in PHP.
Classes are simply defined by using class
keyword in PHP.
While defining your class, do not create your class with name stdClass
in PHP.
– Fatal error : Cannot redeclare class stdClass
– Never create your function of the class starting with "__
" like "__call
". Because you are noticed that magic function in php is started with __
(double underscore).
– Follow some naming convention while creating class (If the class name contains more than one word, we use upper camel case to create class name.)
Classes are nothing without objects. Object is a instance of class. Objects of class can be created by using new
keyword.
$object= new myClass();
Note: PHP OOP allows objects to point out themselves using $this
. You can use $this
while working within a method but if you are working outside of class then you would use the object name.
– You can also create multiple object for a class.
– The process of creating an object is also known as instantiation.
– You can create an object by creating a variable which store the information and using the new
keyword with the name of the class to instantiate from.
$object1= new myClass();
$object2= new myClass();
Example:
As you can see in above image we are creating three objects (Mercedes, Bmw, and Audi.) and all object are created from same class name "car" (We can create many object as we would like from same class) and thus they have the class's methods and properties, they are not same.
This is not only because they have different names but they may have different values assigned to their properties.
As in above image: They are differ by color property in sequence green, blue and orange.
class myClass
{
//variables of the class
public $variable1;
public $variable2;
//Function of class
function addVariables()
{
$result= $this->variable1 + $this->variable2;
return $result;
}
}
$object= new myClass();
$object->variable1=2;
$object->variable2=3;
$sumvalue=$object->addVariables();
echo "Output will be :".$sumvalue;
All Comments