An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
PHP OOP
OOP stands for Object-Oriented Programming. Object-oriented programming is about creating objects that contain both data and functions, this is different from Procedural programming which is about writing procedures or functions that perform operations on the data.
Why OOP?
- OOP is faster and easier to execute
- OOP provides a clear structure for the programs
- OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug
- OOP makes it possible to create full reusable applications with less code and shorter development time
Classes & Objects
Classes and objects are the two main aspects of object-oriented programming.
For example
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the properties and behaviors from the class, but each object will have different values for the properties.
Class
Let assume we have a class Person, a person has a name, age and gender.
To define a class, use curly braces.In a class, variables are called properties and functions are called methods!
<?phpclass Person{ //properties of the class public name; public age; public gender; //methods of the class function setName(name){ $this->name = name; } function getName(){ return $this->name; } function setAge(name){ $this->name = name; } function getAge(){ return $this->name; } function setGender(name){ $this->name = name; } function getGender(){ return $this->name; }}?>
Objects
Classes are nothing without objects! We can create multiple objects from a class. Each object has all the properties and methods defined in the class, but they will have different property values.
Objects of a class is created using the new
keyword.
<?php$person1 = new Person()$person1->setName('samuel')echo "Name:" .$person1->getName()?>
The $this
Keyword
The $this
keyword refers to the current object, and is only available inside methods.
PHP - instanceof
You can use the instanceof
keyword to check if an object belongs to a specific class:
<?php$apple = new Fruit();var_dump($Person1 instanceof Person);?>
Original Link: https://dev.to/bazeng/php-oop-2ilb
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To