3.1 Function and its types
Definition of Function: It is a block of code which may return values or objects on calling.
Types of Functions:
Build in Functions
|
User defined Functions
|
1. It is available with installation package
|
1. It is not available with installation package
|
2. It can be used directly.
|
2. It needs to implement first.
|
3. It cannot be modified as per the requirement.
|
3. It can be made and modified as per the requirement
|
4. Example :
echo(), strtolower(),print_r(),var_dump() etc
|
4 Example:
<?php
function yourAge($age) {
echo "$age is my age \n";
}
|
Terms used in Functions:
Declaring a class & object, Accessing Properties and Methods, Static Class, Abstract Class
Definition:
Classes: It is a user defined data type. Declare using class <class-name>
Objects: It is an instance of a class.
Members: Variables and functions inside class are called members of class.
Properties: Variables inside class are called properties or field or attributes of class.
Method: Functions inside class are called method.
Scope of Object members can be restricted by using following access specifier
1. public: Methods are accessible outside class.
2. private: Methods are accessible inside class.
3. protected: Methods are accessible only for inherited class.
Syntax :
For variable(See “var” is not used here )
public or private or protected $variable-name;
For Method:
public or private or protected $Method-name;
Object Creation using new Operator:
Syntax:
<Class-Name> <Object-Name> = new <Constructor-Name>
Example of Class, Object and Member access Mechanism:
<?php
class NewClass {
public $a;
public $b=" variable constant 1";
public $c=3;
public function newfunc ($arg1, $arg2) {
echo "Hello from method";
}
//other function and variables code here
}
// Below is a way to create Object
$NewObject = new NewClass;
// Below is a function which will give information about variables in Class.
var_dump($NewObject);
//Below is a way to access member variable or method using ‘->’.And remove $ of variable.
echo $NewObject->b."\n";
echo $NewObject->newfunc(3,4);
?>
Output
object(NewClass)#1 (3) {
["a"]=>
NULL
["b"]=>
string(24) "variable constant String"
["c"]=>
int(3)
}
variable constant String
Hello from method
Use of this keyword or operator : $this points to current class and hence its member can be accessed using $this-> <variable-name>
Example:
<?php
class thisDemo
{
public $size ="18";
public function useit(){
return $this->size;//current object member access possible using $this.
}
}
$NewObj = new thisDemo;
echo $NewObj->useit();
?>
Output
18
Scope Resolution Operator (::)
1. It is written by two colons ::
2. It is used to access static constants
3. It is used to access overridden methods or properties of class.
Constant in Classes
1. It is declared by “const” keyword and its value will not change either at compile time or at runtime.
2. Constant variable never starts from $.
3. It can be accessed using $ClassName :: const-variable-name.
4. Interface can use it for defining constants.
Example:
<?php
class ConstDemo
{
const PI =3.14;
function displayit()
{
echo self::PI . “ It is accessed from method\n";
}
}
$nameofclass = 'ConstDemo';
echo $nameofclass::PI . " It has used variable with class name and then access it using variable\n";
$Obj = new ConstDemo;
$Obj->displayit();
echo ConstDemo::PI . " It is directly using classname to access";
?>
Output
3.14 It has used variable with class name and then access it using variable
3.14 It is accessed from method
3.14 It is directly using classname to access
Static Classes
Definition
static:It means a single copy with fixed slot of memory that can have global access.
So based on definition, we have static variable, static methods and static classes.
static variable: variable with a single copy with fixed slot of memory that can have global access.
Static method: method with a single copy with fixed slot of memory that can have global access.
Static class: Class with a single copy with global access.
In Diagram it can be seen that $a and $b are local copies of A1, A2 and A3 that are accessed by Object themselves only but externally only static variable $b is available for all three A1, A2, A3. So if any of the object say A1 change $b from 3 to 4 then A2 can see 4, A3 can see 4. That is globally accessible and hence it is a single copy to share among all Objects.
Diagram 3.1:
Static variable and method Example:
<?php
class A
{
public $a=1,$b=2;
public static $c = 3;
public static function getvalue() {
return A::$c++;
}
}
$A1 = new A;
$A2 = new A;
$A3 = new A;
$A1::$c++;// A1 is Changing static value
$A2::$c++;// A2 is Changing static value
$A3::$c++;// A3 is Changing static value
A::getvalue();//Class A calling static method getvalue which itself calling static value $c.
//Also see it can be accessed by classname or obejct name with scope resoultion operator
echo "This is a final static value\nincremented seperately by A1,A2,A3 then by static method :". A::$c;
?>
Output
This is a final static value
incremented seperately by A1,A2,A3 then by statcic method :73.14 It is accessed from method
Static class Example:
<?php
/*Please refer mentioned link for more details https://stackoverflow.com/questions/468642/is-it-possible-to-create-static-classes-in-php-like-in-c*/
/* Static classes don’t call constructor automatically. We need to used initialize function */
// here self means pointing current classname.
class Hello
{
private static $greeting = 'Hello from Static class';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' Single Copy Initialized!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet();
?>
Output
This is a final static value
incremented separately by A1,A2,A3 then by static method : 7
Use of Static:
1. It is used when we need single copy to be used by every object.
Example: Database Connectivity url.
2. Some constant to be used by everyone
Example: Website domain name “www.dte.org” for making relative links.
Constructor methods:
1. It is just like method which does not have return value.
2. It is used to initialize Object properties.
3. It starts with two underscore ”__” before its name “construct”.
4. It is used only when user need to pass parameter while creating object otherwise default constructor is called automatically.
Syntax:
function __construct (param1, param2…..){
//initialization code.
}
Example of constructor:
<?php
// Define a class
class Area
{
// Declaring two private variables
private $length,$breadth;
// Declarte construct method which accepts two parameters
function __construct($length,$breadth)
{
$this->length = $length;
$this->breadth = $breadth;
}
// Declare a method for calulating area
function calculateArea()
{
return $this->length*$this->breadth;
}
}
// Create a new object and passes two parameters
$rectangle1 = new Area(20,20);
echo "Area of rectangle is : ".$rectangle1->calculateArea();
?>
Output:
Area of rectangle is : 400
Destructor Method
1. It works opposite of constructor.
2. It is used to destroy object.
3. It starts with two underscore “__” with destruct word.
4. Object can also be destroyed by calling function unset();
Syntax:
function __destruct {
//Code
}
Example of Destructor Method:
<?php
// Define a class
class demoClass
{
function __construct()
{
echo "Initialize Object demoClass"."\n";
$this->name = "demoClass";
}
function __destruct()
{
echo "Destroying " . $this->name . "\n";
}
}
$obj = new demoClass();
?>
Output:
Initialize Object demoClass
Destroying demoClass
Inheritance, Overloading and Overriding, Cloning Object.
Inheritance: Use of properties and method of parent class in child class using “extends” is called as inheritance.
It is the mechanism in PHP by which one class is allowed to inherit the features (fields and methods) of another class.
Syntax:
class derived-class extends base-class
{
//methods and fields
}
Inheritance Types and use of public private protected example:
Single Inheritance: B extends properties of A
Example:
<?php
public class A{
public function x(){}
private function y(){}
}
public class B extends A{
//By default x() method is available
//But y() is private , it is not present.
}
?>
Multilevel Inheritance: a derived class will be inheriting a base class and as well as the derived class also act as the base class to other class.
Example:
<?php
public class A{
public function x(){}
protected function y(){}
}
public class B extends A{
//By default x() method is available
// y() will also available here as we are getting it from parent class.
}
public class C extends B{
//By default x() method is available
}
?>
Hierarchical Inheritance: In Hierarchical Inheritance,one class serves as a superclass (base class) for more than one sub class.
Example:
<?php
public class A{
public function x(){}
}
public class B extends A{
//By default x() method is available
protected function y(){}
}
public class C extends A{
//By default x() method is available
//y() is not available as C is not a child class of B.
}
public class D extends A{
//By default x() method is available
}
?>
Abstract Class and Interface:
Definition:
Abstract Class: It is class having at-least one method declared without body {}, prefixed with abstract keyword.
Interface: It is a pure abstract class which has strict set of methods and constant that has to be implemented by child class. Below is an example of multiple inheritances where interface and abstract classes can be used.
Multiple Inheritances (Through Interfaces): Here one class can have more than one superclass and it will inherit features from all parent classes.


Example:
<?php
public Interface A {
public abstract function x();
}
public Interface B {
public abstract function y();
}
public class C implements A,B{
//Mandatory override
public function x(){}
public function y{}
}
?>
Hybrid Inheritance (Through Interfaces): It is a mix of hierarchy and multiple inheritances.
Example:
<?php
public Interface A {
public abstract function x();
}
public interface B extends A {
public abstract function y();
}
public interface C extends A{
// override
public function x();
public function y();
}
public class D implements B,C{
//All methods need to be implemented here.
}
?>
Difference in Abstract and Interface:
Abstract Class
|
Interface
|
1. It has member method with and without {}
|
1. It has member method without {} only.
|
2. Does not support Multiple inheritance
|
2. Support Multiple inheritance
|
3. It contains constructors
|
3. It does not have constructors
|
4. It contains data member
|
4. It does not contain data member.
|
5. Example
<?php
abstract class A {
public $a=3;
abstract function x();
public function y(){
echo "Method inside Abstract Class A";
}
}
class B extends A{
function x(){
echo "x method implemented";
}
}
$a = new B;
$a->x();
$a->y();
?>
Output:
Method inside Abstract Class A
x method implemented
|
5. Example
<?php
interface A {
function x();
}
class B implements A{
function x(){
echo "Method from A Interface";
}
}
$C = new B;
$C->x();
?>
Output:
Method from A Interface
|
Difference in Overloading and Overriding:
Overloading
|
Overriding
|
1. It has same name of function only.
|
1. It has same name and same parameters also
|
2. Uses magic functions
|
2. No need of magic functions
|
3. There are 2 types of overloading.
|
3. There is only one type of Overriding.
|
4. Example with function Overloading:
<?php
// explanation of function overloading
class calculate {
// __call is magic function which is accepting
// function name and arguments
function __call($function_name, $parameters) {
// check the function name
if($function_name == 'sum') {
switch (count($parameters)) {
// for 1 parameter
case 1:
return $parameters[0];
// for 2 parameters
case 2:
return $parameters[0]+$parameters[1];
}
}
}
}
//Object declaration
$c = new calculate;
// call func
echo($c->sum(10));
echo "\n";
// call with 2 parameters
echo ($c->sum(10, 10));
?>
Output:
10
20
|
4. Example with function Overriding.
<?php
interface A {
function x();}
class B implements A{
//Overriding Method mandatory
function x(){
echo "Method from A Override";
}
}
$C = new B;
$C->x();
?>
Output:
Method from A Override
|
Property Overloading:
Unlike Java in PHP we have Property Overloading also. For that we need to understand magic methods first. Following methods are called as magic methods in php:
public __set ( string $name , mixed $value ) : void => to assign data.
public __get ( string $name ) : mixed=> to receive data.
public __isset ( string $name ) : bool=> to check values are set or not.
public __unset ( string $name ) : void => to clear the assigned values.
Example of Property Overloading:
<?php
class PropertyTest
{
/** Location for overloaded data. */
private $data = array();
/** Overloading not used on declared properties. */
public $declared = 1;
/** Overloading only used on this when accessed outside the class. */
private $hidden = 2;
public function __set($name, $value)
{
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name)
{
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
/** As of PHP 5.1.0 */
public function __isset($name)
{
echo "Is '$name' set?\n";
return isset($this->data[$name]);
}
/** As of PHP 5.1.0 */
public function __unset($name)
{
echo "Unsetting '$name'\n";
unset($this->data[$name]);
}
/** Not a magic method, just here for example. */
public function getHidden()
{
return $this->hidden;
}
}
echo "<pre>\n";
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n\n";
var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";
echo $obj->declared . "\n\n";
echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>
Output:
PHP Notice: Undefined property via __get(): hidden in source_file.php on line 75 in source_file.php on line 31
Setting 'a' to '1'
Getting 'a'
1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'
Cloning Object: A method used to make a copy of object is called as cloning.
In PHP cloning is done using a magic method __clone ( void ) : void. When cloning is done an empty copy of all object’s properties and method is created. So the object structure is same but its values can be changed.
Use of Cloning Method:
1. It saves the processing task for creating a exact copy of object.
2. For testing, copy of object can be used by changing data frequently.
Example of cloning:
<?php
class Students
{
public $name;
public $branch;
}
//Creating instance of student class
$objStudents = new Students();
//Assigning values
$objStudents->name = "Aditya";
$objStudents->branch = "Computer Science";
//Cloning the original object
$objClonedCopy = clone $objStudents;
$objClonedCopy->name = "Aditi";
$objClonedCopy->branch = "Information Technology";
print_r($objStudents);
print_r($objClonedCopy);
?>
Output:
Students Object
(
[name] => Aditya
[branch] => Computer Science
)
Students Object
(
[name] => Aditi
[branch] => Information Technology
)
Introspection:
Definition: It is a process of identifying features of object such as class-name, existence information, parent class or subclass information etc.
Following are the some of the Introspection functions:
1. class_exists() – To check if class is defined or not.
2. get_class() – To return the class name of object.
3. get_parent_class() – To return the class name of Parent class of Object .
4. is_subclass_of() – To check if class is a subclass of some other parent class.
Example of Introspection:
<?php
class IntrospectionDemo
{
public function Info() {
echo "<br> It is a super class";
}
}
class ChildDemo extends IntrospectionDemo
{
public function Info() {
echo "<br> This class Name is " . get_class($this);
echo "<br> Its Parent class Name is " . get_parent_class($this);
}
}
if (class_exists("IntrospectionDemo")) {
$newClass = new IntrospectionDemo();
echo "<br> If exsist its name is : " . get_class($newClass);
$newClass->Info();
}
$childClass = new ChildDemo();
$childClass->Info();
if (is_subclass_of($childClass, "IntrospectionDemo")) {
echo "<br> Is it subclass : Yes";
}
else {
echo "<br> Is it subclass : No";
}
Output:
If exsist its name is : IntrospectionDemo
It is a super class
This class Name is ChildDemo
Its Parent class Name is IntrospectionDemo
Is it subclass : Yes
Serialization:
Definition: It is a process of converting objects into byte stream.
For Serialization, PHP has serialize() and unserialize() function.
1. serialize() : Convert Object to Byte stream.
2. unserialize() : Convert Byte stream to Object.
Example of Serialization:
<?php
$serialized = serialize(array('It', 'is', 'You'));
echo $serialized. '<br>';
$rev = unserialize($serialized);
// Show it in array form again
var_dump ($rev);
Output:
a:3:{i:0;s:2:"It";i:1;s:2:"is";i:2;s:3:"You";}
array(3) { [0]=> string(2) "It" [1]=> string(2) "is" [2]=> string(3) "You" }






No comments:
Post a Comment