Object-Oriented-PHP - Classes
A class provides the definition of an object and it serves as a template for creating new objects.
Defining classes
To get a list of all the available classes, PHP has the function: get_declared_classes().
$classes= get_declared_classes();
print_r($classes);
To define a new class:
class SimpleClass {
// code goes here...
}
To check if a class exists there is the function class_exists, that receives a string and returns a boolean.
if (class_exists("SimpleClass")){
echo "True";
} else{
echo "False";
}
//true
Instances
Once a class has been declared we can call it by its name, and assign it to a variable. This process is called instantiation, where we instantiate an object from a class.
$obj= new SimpleClass; //creates a new object from the class SimpleClass
echo get_class($obj); // returns the name of the object class (SimpleClass)
Class Properties
Properties are variables, attributes that hold object values.
Define properties using var $VariableName
class SimpleClass {
var $prop1 = "something";
var $prop2 = 3;
}
To acess the properties:
$obj= new SimpleClass;
echo $obj->prop1;
//something
echo $obj->prop2;
//3
Functions for properties
- get_class_var($string) - returns a list of properties defined in the class:
print_r(get_class_vars("SimpleClass"));
//Array ( [prop1] => something [prop2] => 3 )
- get_object_vars($object) - returns a list of properties assigned to the object:
print_r(get_object_vars($obj));
//Array ( [prop1] => something [prop2] => 3 )
- property_exists($mixed, $string) - checks if the object or class has a property.
if (property_exists("SimpleClass", "prop2")){
echo "True";
} else{
echo "False";
}
//true
Class methods
Methods are functions inside classes to perform object actions.
class SimpleClass {
//properties
var $prop1 = "something";
var $prop2 = 3;
//method
function say_hello(){
return "Hello world!";
}
}
To execute the method:
$obj= new SimpleClass;
echo $obj->say_hello();
//Hello world!
Refer to an instance
If we try to access the properties inside the function, it will not work.
class SimpleClass {
//properties
var $prop1 = "something";
var $prop2 = 3;
//method
function say_hello(){
return $prop1;
}
}
$obj= new SimpleClass;
echo $obj->say_hello();
//Undefined variable: prop1
To solve this problem we need to use the variable this:
class SimpleClass {
var $prop1 = "something";
var $prop2 = 3;
function say_hello(){
return $this->prop1;
}
}
$obj= new SimpleClass;
echo $obj->say_hello();
//something
Functions for methods
- get_class_methods($mixed)
- method_exists($mixed, $string)