If you are pursuing a web development course and want to excel in it then learning PHP is necessary for you. When it comes to PHP then learning objects comes among top common things. So, let's see what they are and how to use them with the blog.
Objects in php are used with classes, we can create multiple objects of a class. Each objects will have the all of the properties and the methods of the class, we can create objects of a class with new keyword. New keyword is used to initiate the object of a class. Object is an instance it is either created by a user or it is already built in. Arrays and other objects can be type cast to the object data type using casting operator in php.
Here is an example of how to use new keyword:
classMyClass {
public $name = "Wasim";
}
$obj = new MyClass(); //Initiating object
echo "The name is " .$obj->name;
?>
Let’s see an example of array being type cast to the object:
$arr = array(“name” => “Wasim”, “age” => 24, “marks” => 75);
$obj = (object)$arr; //Type Casting object
print_r($obj);
?>
Output:
stdClass Object
(
[name] => Wasim
[age] => 24
[marks] => 75
)
Let’s see the example of the objects in php and how it’s works:
class Student{
// Public properties of class
public $name;
public $course;
//Methods of the class
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$stud1 = new Student();
$stud2 = new Student();
$stud1->set_name('Wasim’);
$stud2->set_name('SKP');
echo $stud1->get_name();
echo "
";
echo $stud2->get_name();
?>
In the example above, we have declare a class name student, in this class we have declare two public properties name and course which we are accessing in the setter and getter methods of the class.
We have created two objects variables and initiated their instance using the new keyword.
Instanceof keyword
Instanceof keyword of php is used to check that if the object is belong to a specific class or not.
Let’s see an example of it:
class Student {
// Properties
public $name;
public $color;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
}
$stud = new Student();
var_dump($stud instanceof Student); // Output: bool(true)
?>
$this keyword
In php this keyword will always refersto the current object and can be used only inside the methods. It’s pretty muchsimilar to the javascript this keyword.
Let’s see an example of using this keyword in php:
class Student{
public $name;
function set_name($name){
$this->name = $name;
}
}
$stud= new Student();
$stud->set_name("Wasim");
echo $stud->name;
?>
That all about the objects. There is still more to explore and that you can do with a professional PHP course in Delhi from a reputed web development training institute.