Classes and Objects
Introduction
Class
is as like a blueprint for a house
. and Objects
is actual house
following by buleprint .
Class is declared by class
key and pair of {}
curly braces
constants+variables
are calledproperty
Functions
are calledmethod
class structure
<?phpclass SimpleClass{// property declarationpublic $var = 'a default value';// method declarationpublic function displayVar() {echo $this->var;}}?>
Basics
Propertis
Class member variables are property . Property type public
, protected
, and private
.
Accessing property inside method
- $this->foo (Non static)
- $self::$foo (static) by double
::
Class constants
Constant variable means variable value is always unchangable . Constant variable is defined by const
without $
sign . Constant visibility is always public
.
|
Autoloading Classes
Constructor And Destructor
A constructor and a destructor are special functions which are automatically called when an object is created and destroyed. The constructor is the most useful of the two, especially because it allows you to send parameters along when creating a new object, which can then be used to initialize variables on the object. Here’s an example of a class with a simple constructor:
|
Destructors
A destructor is called when the object is destroyed. In some programming languages, you have to manually dispose of objects you created, but in PHP, it’s handled by the Garbage Collector, which keeps an eye on your objects and automatically destroys them when they are no longer needed. Have a look at the following example, which is an extended version of our previous example:
Visibilty
The visibility of a property, a method or (as of PHP 7.1.0) a constant can be defined by prefixing the declaration with the keywords public
, private
or protected
.
Class
- members declared
public
can be accessedeverywhere
. - Members declared as
private
may only be accessed by the class thatdefines the member
. Members declared
protected
can be accessed only within the classitself
and byinheriting
classes.public
class test{public $abc;public $xyz;public function xyz(){}}$objA = new test();echo $objA->abc;//accessible from outside$objA->xyz();//public method of the class testprivate
Class test{public $abc;private $xyz;public function pubDo($a){echo $a;}private function privDo($b){echo $b;}public function pubPrivDo(){$this->xyz = 1;$this->privDo(1);}}$objT = new test();$objT->abc = 3;//Works fine$objT->xyz = 1;//Throw fatal error of visibility$objT->pubDo("test");//Print "test"$objT->privDo(1);//Fatal error of visibility//Within this method private function privDo and variable xyz is called using $this variable.$objT->pubPrivDo();protected
class parent{protected $pr;public $aprotected function testParent(){echo this is test;}}class child extends parent{public function testChild(){$this->testParent(); //will work}}$objParent = new parent();$objParent->testParent();//Throw error$objChild = new Child();//work because test child will call test parent.$objChild->setChild();
Object Inheritance
One of the main advantages of object-oriented programming is the ability to reduce code duplication with inheritance. Code duplication occurs when a programmer writes the same code more than once, a problem that inheritance strives to solve. In inheritance, we have a parent class with its own methods and properties, and a child class (or classes) that can use the code from the parent. By using inheritance, we can create a reusable piece of code that we write only once in the parent class, and use again as much as we need in the child classes.
In order to declare that one class inherits
the code from another class, we use the extends
keyword. Let’s see the general case:
Scope resolution operator (::)
The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static
, constant
, and overridden properties or methods of a class.
Three special keywords self
, parent
and static
are used to access properties or methods from inside the class definition.
- Calling Parent methods<?phpclass MyClass{protected function myFunc() {echo "MyClass::myFunc()\n";}}class OtherClass extends MyClass{// Override parent's definitionpublic function myFunc(){// But still call the parent functionparent::myFunc();echo "OtherClass::myFunc()\n";}}$class = new OtherClass();$class->myFunc();?>
Static Keyword
Static methods and properties in php is very useful feature. Static methods and properties in php can directly accessible without
creating object of class
. Your php class will be static class if your all methods and properties of the class is static. Static Methods and Properties in PHP will be treated as public if no visibility is defined.
|
- ex.2<?phpclass Counter{private $count;public static $instance;public function __construct($count = 0){$this->count = $count;self::$instance++;}public function count(){$this->count++;return $this;}public function __toString(){return (string)$this->count;}public static function countInstance(){return self::$instance;}}$c1 = new Counter();$c1->count()->count();echo 'Counter 1 value: '. $c1 . '<br/>';$c2 = new Counter();$c2->count()->count()->count();echo 'Counter 2 value: '. $c2 . '<br/>';echo 'The number of counter instances:'. Counter::countInstance(). '<br/>';
Class Abstraction
An abstract class is a class that has at least one abstract method
. Abstract methods can only have names and arguments, and no other code
. Thus, we cannot create objects out of abstract classes. Instead, we need to create child classes that add the code into the bodies of the methods, and use these child classes to create
objects.
- Your any class has at least one method Abstract than your class is abstract .
- You can’t make object of abstract class, only can extend abstract class.
- Usually abstract class are also known as
base class
.
|
- ex. 2<?phpabstract class AbstractClass{// Force Extending class to define this methodabstract protected function getValue();abstract protected function prefixValue($prefix);// Common methodpublic function printOut() {print $this->getValue() . "\n";}}class ConcreteClass1 extends AbstractClass{protected function getValue() {return "ConcreteClass1";}public function prefixValue($prefix) {return "{$prefix}ConcreteClass1";}}class ConcreteClass2 extends AbstractClass{public function getValue() {return "ConcreteClass2";}public function prefixValue($prefix) {return "{$prefix}ConcreteClass2";}}$class1 = new ConcreteClass1;$class1->printOut();echo $class1->prefixValue('FOO_') ."\n";$class2 = new ConcreteClass2;$class2->printOut();echo $class2->prefixValue('FOO_') ."\n";?>
Object Interfaces
An interface allows you to specify a list of methods that a class must implement. To define an interface, you use the interface keyword as follows:
- ex. 2
|
Trait
Anonymous classes
Overloading
PHP’s interpretation of “overloading” is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.
magic method is use for overloading in php.
Property overloading
public void __set ( string $name , mixed $value )public mixed __get ( string $name )public bool __isset ( string $name )public void __unset ( string $name )Method overloading
public mixed __call ( string $name , array $arguments )public static mixed __callStatic ( string $name , array $arguments )
Object Iteration
Magic Methods
The magic
methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events
|
Final keywords
In PHP, Final Keyword is applicable to only class
and class methods
. We can not declare variables as Final in PHP.So if you declare class method as a Final then that method can not be override by the child class. Same as method if we declare class as a Final then that class can not be extended any more.
Declaring Class as Final -
Below code will end up with this error: Class child_class may not inherit from final class (parent_class)// This class can not be Extendedfinal class parent_class{public function class_method(){/*Code Here*/}}class child_class extends parent_class{public function class_method(){/*Code Here*/}}Declaring Class Method as Final
Below code will end up with this error: Cannot override final method parent_class::class_method()
|
Object Cloning
reating a copy of an object with fully replicated properties is not always the wanted behavior. A good example of the need for copy constructors, is if you have an object which represents a GTK window and the object holds the resource of this GTK window, when you create a duplicate you might want to create a new window with the same properties and have the new object hold the resource of the new window. Another example is if your object holds a reference to another object which it uses and when you replicate the parent object you want to create a new instance of this other object so that the replica has its own separate copy.
An object copy is created by using the clone keyword (which calls the object’s __clone()
method if possible). An object’s __clone()
method cannot be called directly.
$copy_of_object = clone $object;
|
- with magic method
__clone
<?phpclass test{public $a;private $b;function __construct($a, $b){$this->a = $a;$this->b = $b;}function __clone(){$this->a = "c";}}$a = new test("ankur" , "techflirt");$b = $a; //Copy of the object$c = clone $a; //clone of the object$a->a = "no Ankur";print_r($a);print_r($b);print_r($c);print_r($a);
Comparing Object
When using the comparison operator (==), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with ==), and are instances of the same class.
When using the identity operator (===), object variables are identical if and only if they refer to the same instance of the same class.
ex. 1
<?phpfunction bool2str($bool){if ($bool === false) {return 'FALSE';} else {return 'TRUE';}}function compareObjects(&$o1, &$o2){echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n";}class Flag{public $flag;function Flag($flag = true) {$this->flag = $flag;}}class OtherFlag{public $flag;function OtherFlag($flag = true) {$this->flag = $flag;}}$o = new Flag();$p = new Flag();$q = $o;$r = new OtherFlag();echo "Two instances of the same class\n";compareObjects($o, $p);echo "\nTwo references to the same instance\n";compareObjects($o, $q);echo "\nInstances of two different classes\n";compareObjects($o, $r);?>Result
-Two instances of the same classo1 == o2 : TRUEo1 != o2 : FALSEo1 === o2 : FALSEo1 !== o2 : TRUETwo references to the same instanceo1 == o2 : TRUEo1 != o2 : FALSEo1 === o2 : TRUEo1 !== o2 : FALSEInstances of two different classeso1 == o2 : FALSEo1 != o2 : TRUEo1 === o2 : FALSEo1 !== o2 : TRUE