SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Object oriented programming in PHP 
• PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.), 
supports the creation of objects. 
• Creating an object requires you to first define an object class (containing variables 
and/or function definitions) and then using the “new” keyword to create an instance of 
the object class. (Note that the object must be defined before you instantiate it.) 
<?php 
// Assume that the "Person" object has been previously defined. . . 
$x = new Person; // creates an instance of the Person class (*no* quotes) 
// The object type need not be "hardcoded" into the declaration. 
$object_type = 'Person'; 
$y = new $object_type; // equivalent to $y = new Person; 
$z = new Vehicle('Jaguar','green'); // creating an object and passing 
// arguments to its constructor 
?>
Defining (declaring) a class 
• Use the “class” keyword which includes the class name (case-insensitive, but 
otherwise following the rules for PHP identifiers). Note: The name “stdClass” is 
reserved for use by the PHP interpreter. 
<?php 
class Person 
{ 
var $name; 
function set_name($new_name) { 
$name = $this -> new_name; 
} 
function get_name() { 
return $this -> name; 
} 
} 
• Use the “$this” variable when accessing properties and functions of the current 
object. Inside a method this variable contains a reference to the object on which 
the method was called.
Declaring a class (cont.) 
• Properties and functions can be declared as “public” (accessible outside the 
object’s scope), “private” (accessible only by methods within the same class), or 
“protected” (accessible only through the class methods and the class methods of 
classes inheriting from the class. 
• Note that unless a property is going to be explicitly declared as public, private, or 
protected, it need not be declared before being used (like regular PHP variables). 
<?php 
class Person 
{ 
protected $name; 
protected $age; 
function set_name($new_name) { 
$name = $this -> new_name; 
} 
function get_name() { 
return $this -> name; 
} 
}
Declaring a class (cont.) 
• Classes can also have their own constants defined (using the “const” keyword), 
can have their own static properties and functions (using the keyword “static” 
before “var” or “function”), and can also can constructors and destructors (see 
below). 
• Static properties and functions are accessed (see below) using a different format 
than usual for objects, and static functions cannot access the objects properties 
(i.e. the variable $this is not defined inside of a static function). 
<?php 
class HTMLtable { 
static function start() { 
echo "<table> n"; 
} 
static function end() { 
echo "</table> n"; 
} 
} 
HTMLtable::start();
Accessing properties and methods 
• Once you have an object, you access methods and properties (variables) of the 
object using the -> notation. 
<?php 
$me = new Person; 
$me -> set_name('Russ'); 
$me -> print_name(); 
$name = $me -> get_name(); 
echo $me -> get_name(); 
$age = 36; 
$me -> set_age($age); 
?>
Constructors and destructors 
• Constructors are methods that are (generally) used to initialize the object’s 
properties with values as the object is created. Declare a constructor function in an 
object by writing a function with the name __construct(). 
<?php 
class Person { 
protected $name; 
protected $age; 
function __construct($new_name, $new_age) { 
$this -> name = $new_name; 
$this -> age = $new_age; 
} 
// . . . other functions here . . . 
} 
$p = new Person('Bob Jones', 45); 
$q = new Person('Hamilton Lincoln', 67); 
?> 
• Destructors (defined with a function name of __destructor() ) are called when an 
object is destroyed, such as when the last reference to an object is removed or the 
end of the script is reached (the usefulness of destructors in PHP is limited, since, 
for example dynamic memory allocation isn’t possible in the same way that it is in 
C/C++).
Inheritance 
• Use the “extends” keyword in the class definition to define a new object that inherits 
from another. 
<?php 
class Employee extends Person { 
var $salary; 
function __construct($new_name, $new_age, $new_salary); { 
$this -> salary = $new_salary; 
parent::__construct($new_name, $new_age); // call the constructor 
// of parent object 
} 
function update_salary($new_salary) { 
$this -> salary = $new_salary; 
} 
$emp = new Employee('Dave Underwood', 25, 25000); 
?>
Inheritance (cont.) 
• The constructor of the parent isn’t called unless the child explicitly references it (as 
in this previous case). There is no automatic chain of calls to constructors in a 
sequence of objects defined through inheritance. 
• You could “hard-code” the call to the parent constructor using the function call 
“Person::__construct($new_name, $new_age);” but it’s typically better to define 
it in the manner given using the parent::method() notation. The same manner is 
used to call the method of a parent that has been overridden by its child. 
• You can use the “self” keyword to ensure that a method is called on the current 
class (if a method might be subclassed), in this style self::method(); 
• To check if an object is of a particular class, you can use the instanceof 
operator. 
if ($p instanceof Employee) { 
// do something here 
}
More on classes 
• You can also define interfaces for objects (for which any object that uses that 
interface must provide implementations of certain methods), and you can define 
abstract classes or methods (that must be overridden by its children). 
• The keyword “final” can be used to denote a method that cannot be overridden by 
its children. 
class Person { 
var $name; 
final function get_name() { 
return $this -> name; 
} 
}
More on classes (cont.) 
• There are methods for “introspection” about classes, i.e. the ability of a program to 
examine an object’s characteristics. 
For example, the function class_exists() can be used (surprise!) to determine 
whether a class exists or not. 
The function get_declared_classes() returns an array of declared classes. 
$classes = get_declared_classes(); 
You can also get an array of method names in any of the following (equivalent) 
manners: 
$methods = get_class_methods(Person); 
$methods = get_class_methods('Person'); 
$class = 'Person'; 
$methods = get_class_methods($class);
More introspection functions 
• There are a wide variety of introspection functions, several more are listed below. 
get_class_vars($object); /* gets an associative array that maps 
property names to values (including 
inherited properties), but it *only* 
gets properties that have default 
values (those initialized with 
simple constants) */ 
is_object($object); // returns a boolean value 
get_class($object); /* returns the class to which an object 
belongs */ 
method_exists($object, $method); // returns a boolean value 
get_object_vars($object); /* returns an associative array 
mapping properties to values (for 
those values that are set (i.e. 
not null) */
A word about object methods… 
• When defining the names of your own object methods, you should generally avoid 
starting them with a double underscore. Why? 
• There are some “built-in” or predefined PHP method names that start in this 
manner, most notably constructors and destructors using the __construct() and 
__destructor() names. In the future (in new versions of PHP), it’s possible that 
further methods might be defined that begin with a double underscore. 
• Other reserved method names include __sleep() and __wakeup() which are used 
for object serialization and __get() and __set(), which can be defined so that if you 
try to access an object property that doesn’t exist, these methods give an 
opportunity to either retrieve a value or set the (default?) value for that property. 
For example, if a class is used to represent data obtained from a database, you 
could write __get() and __set() methods that read and write data whenever 
requested.
PHP sessions 
• By default, HTML and web servers don’t keep track of information entered on a 
page when the client’s browser opens another page. Thus, doing anything 
involving the same information across several pages can sometimes be difficult. 
• Sessions help solve this problem by maintaining data during a user’s visit, and can 
store data that can be accessed from page to page in your site. 
• You can use session variables for storing information (this is one way that a 
“shopping cart” function can work for an online shop, for example). 
• Servers keep track of users’ sessions by using a session identifier, which is 
generated by the server when a session starts and is then used by the browser 
when it requests a page from the server. This session ID can be sent through a 
cookie (the default behavior) or by passing the session ID in the URL string. 
• Sessions only store information temporarily, so if you need to preserve information, 
say, between visits to the same site, you should likely consider a method such as 
using a cookie or a database to store such information.
PHP sessions (cont.) 
• To start a session, use the function session_start() at the beginning of your PHP script 
before you store or access any data. For the session to work properly, this function 
needs to execute before any other header calls or other output is sent to the browser. 
<?php 
session_start(); 
?> 
<!DOCTYPE html PUBLIC "-//Www//DTD XHTML 1.0 Transitional//EN" 
"http://www.abc.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<title>Session example</title> 
</head> 
<body> 
<?php 
include_once ('object.php'); // Includes definition of the Person class 
$_SESSION['hello'] = 'Hello world'; 
echo $_SESSION['hello'] . "<br/><br/>n"; 
$_SESSION['one'] = 'one'; 
$_SESSION['two'] = 'two'; 
$me = new Person("Russ", 36, 2892700); 
$_SESSION['name'] = $me->get_name(); 
echo "Testing " . $_SESSION['one'] .", " . $_SESSION['two'] . ", " . $me- 
>get_number() . " . . .<br/>n"; 
?> 
</body></html> 
view the output page
Using session variables 
• Once a session variable has been defined, you can access it from other pages. 
<?php 
session_start(); 
?> 
<!DOCTYPE html PUBLIC "-//abc//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<title>Session example 2</title> 
</head> 
<body> 
<?php 
echo "Welcome to a new page ". $_SESSION['name'] "!<br/>n"; 
echo "Hope you enjoy your stay! <br/>"; 
?> 
<p>Back to regular HTML text... 
</p> 
</body> 
</html> view the output page
More on session variables 
• You need to include a call to the session_start() function for each page on which 
you want to access the session variables. 
• A session will end once you quit the browser (unless you’ve set appropriate 
cookies that will persist), or you can call the session_destroy() function. (Note, 
however, even after calling the session_destroy() function, session variables are 
still available to the rest of the currently executing PHP page.) 
• The function session_unset() removes all session variables. If you want to remove 
one variable, use the unset($var) function call. 
• The default timeout for session files is 24 minutes. It’s possible to change this 
timeout.
Deleting all session variables 
<?php 
session_start(); 
?> 
<!DOCTYPE html PUBLIC "-//abc//DTD XHTML 1.0 Transitional//EN" 
"http://www.abc.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
<title>Session example 3</title> 
</head> 
<body> 
<?php 
echo "Deleting all session variables using session_unset(); <br/>n"; 
session_unset(); 
echo "Now the session variables are gone. <br/>n"; 
if (isset($_SESSION['name'])) 
{ echo $_SESSION['name'] . "<br/>n"; } 
else 
{ echo "Session variable is not here."; } 
?> 
</body> 
</html> 
view the output page
Learning Outcomes 
• A (very, very brief) introduction to objects in PHP. If you 
wish to use objects, then many books on PHP include more 
information, and, of course, much information is available 
online. 
• Sessions are useful for persistence of variables across 
many webpages without the need to submit information via 
forms.

Weitere ähnliche Inhalte

Was ist angesagt?

PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHPVibrant Technologies & Computers
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHPRamasubbu .P
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3Toni Kolev
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5Jason Austin
 
Oop in-php
Oop in-phpOop in-php
Oop in-phpRajesh S
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHPDavid Stockton
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHPMichael Peacock
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classesKumar
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in phpCPD INDIA
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonSujith Kumar
 

Was ist angesagt? (20)

Oops in PHP
Oops in PHPOops in PHP
Oops in PHP
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Php Oop
Php OopPhp Oop
Php Oop
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Class and Objects in PHP
Class and Objects in PHPClass and Objects in PHP
Class and Objects in PHP
 
FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3FFW Gabrovo PMG - PHP OOP Part 3
FFW Gabrovo PMG - PHP OOP Part 3
 
Ch8(oop)
Ch8(oop)Ch8(oop)
Ch8(oop)
 
Object Oriented PHP5
Object Oriented PHP5Object Oriented PHP5
Object Oriented PHP5
 
Oop in-php
Oop in-phpOop in-php
Oop in-php
 
Intermediate OOP in PHP
Intermediate OOP in PHPIntermediate OOP in PHP
Intermediate OOP in PHP
 
Oops in php
Oops in phpOops in php
Oops in php
 
Introduction to OOP with PHP
Introduction to OOP with PHPIntroduction to OOP with PHP
Introduction to OOP with PHP
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
 
Basics of Object Oriented Programming in Python
Basics of Object Oriented Programming in PythonBasics of Object Oriented Programming in Python
Basics of Object Oriented Programming in Python
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
 
Python oop third class
Python oop   third classPython oop   third class
Python oop third class
 

Ähnlich wie Synapseindia object oriented programming in php

Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxShaownRoy1
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeDhivyaa C.R
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Alena Holligan
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpAlena Holligan
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPSxoopsproject
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2Mudasir Syed
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in phpAashiq Kuchey
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHPRohan Sharma
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Alena Holligan
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfGammingWorld2
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Alena Holligan
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptxrani marri
 
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Rathod Shukar
 

Ähnlich wie Synapseindia object oriented programming in php (20)

Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16Demystifying Object-Oriented Programming #ssphp16
Demystifying Object-Oriented Programming #ssphp16
 
Only oop
Only oopOnly oop
Only oop
 
Take the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphpTake the Plunge with OOP from #pnwphp
Take the Plunge with OOP from #pnwphp
 
OOP Adventures with XOOPS
OOP Adventures with XOOPSOOP Adventures with XOOPS
OOP Adventures with XOOPS
 
Oop in php lecture 2
Oop in  php lecture 2Oop in  php lecture 2
Oop in php lecture 2
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
Object oriented programming in php
Object oriented programming in phpObject oriented programming in php
Object oriented programming in php
 
Basic Oops concept of PHP
Basic Oops concept of PHPBasic Oops concept of PHP
Basic Oops concept of PHP
 
Introduction Php
Introduction PhpIntroduction Php
Introduction Php
 
Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017Demystifying Object-Oriented Programming - PHP UK Conference 2017
Demystifying Object-Oriented Programming - PHP UK Conference 2017
 
Object_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdfObject_oriented_programming_OOP_with_PHP.pdf
Object_oriented_programming_OOP_with_PHP.pdf
 
Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017Demystifying Object-Oriented Programming - PHP[tek] 2017
Demystifying Object-Oriented Programming - PHP[tek] 2017
 
OOPS IN PHP.pptx
OOPS IN PHP.pptxOOPS IN PHP.pptx
OOPS IN PHP.pptx
 
Jscript part2
Jscript part2Jscript part2
Jscript part2
 
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
Wordpress (class,property,visibility,const,destr,inheritence,mysql etc)
 
Chapter iii(oop)
Chapter iii(oop)Chapter iii(oop)
Chapter iii(oop)
 

Mehr von Synapseindiappsdevelopment

Synapse india elance top in demand in it skills
Synapse india elance top in demand in it skillsSynapse india elance top in demand in it skills
Synapse india elance top in demand in it skillsSynapseindiappsdevelopment
 
SynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture moduleSynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture moduleSynapseindiappsdevelopment
 
SynapseIndia dotnet development platform overview
SynapseIndia  dotnet development platform overviewSynapseIndia  dotnet development platform overview
SynapseIndia dotnet development platform overviewSynapseindiappsdevelopment
 
SynapseIndia dotnet web applications development
SynapseIndia  dotnet web applications developmentSynapseIndia  dotnet web applications development
SynapseIndia dotnet web applications developmentSynapseindiappsdevelopment
 
SynapseIndia dotnet website security development
SynapseIndia  dotnet website security developmentSynapseIndia  dotnet website security development
SynapseIndia dotnet website security developmentSynapseindiappsdevelopment
 
SynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architectureSynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architectureSynapseindiappsdevelopment
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseindiappsdevelopment
 
SynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architectureSynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architectureSynapseindiappsdevelopment
 
SynapseIndia dotnet client library Development
SynapseIndia dotnet client library DevelopmentSynapseIndia dotnet client library Development
SynapseIndia dotnet client library DevelopmentSynapseindiappsdevelopment
 
SynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseindiappsdevelopment
 

Mehr von Synapseindiappsdevelopment (20)

Synapse india elance top in demand in it skills
Synapse india elance top in demand in it skillsSynapse india elance top in demand in it skills
Synapse india elance top in demand in it skills
 
SynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture moduleSynapseIndia dotnet web development architecture module
SynapseIndia dotnet web development architecture module
 
SynapseIndia dotnet module development part 1
SynapseIndia  dotnet module development part 1SynapseIndia  dotnet module development part 1
SynapseIndia dotnet module development part 1
 
SynapseIndia dotnet framework library
SynapseIndia  dotnet framework librarySynapseIndia  dotnet framework library
SynapseIndia dotnet framework library
 
SynapseIndia dotnet development platform overview
SynapseIndia  dotnet development platform overviewSynapseIndia  dotnet development platform overview
SynapseIndia dotnet development platform overview
 
SynapseIndia dotnet development framework
SynapseIndia  dotnet development frameworkSynapseIndia  dotnet development framework
SynapseIndia dotnet development framework
 
SynapseIndia dotnet web applications development
SynapseIndia  dotnet web applications developmentSynapseIndia  dotnet web applications development
SynapseIndia dotnet web applications development
 
SynapseIndia dotnet website security development
SynapseIndia  dotnet website security developmentSynapseIndia  dotnet website security development
SynapseIndia dotnet website security development
 
SynapseIndia mobile build apps management
SynapseIndia mobile build apps managementSynapseIndia mobile build apps management
SynapseIndia mobile build apps management
 
SynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architectureSynapseIndia mobile apps deployment framework internal architecture
SynapseIndia mobile apps deployment framework internal architecture
 
SynapseIndia java and .net development
SynapseIndia java and .net developmentSynapseIndia java and .net development
SynapseIndia java and .net development
 
SynapseIndia dotnet development panel control
SynapseIndia dotnet development panel controlSynapseIndia dotnet development panel control
SynapseIndia dotnet development panel control
 
SynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client librarySynapseIndia dotnet development ajax client library
SynapseIndia dotnet development ajax client library
 
SynapseIndia php web development
SynapseIndia php web developmentSynapseIndia php web development
SynapseIndia php web development
 
SynapseIndia mobile apps architecture
SynapseIndia mobile apps architectureSynapseIndia mobile apps architecture
SynapseIndia mobile apps architecture
 
SynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architectureSynapseIndia mobile apps deployment framework architecture
SynapseIndia mobile apps deployment framework architecture
 
SynapseIndia mobile apps
SynapseIndia mobile appsSynapseIndia mobile apps
SynapseIndia mobile apps
 
SynapseIndia dotnet development
SynapseIndia dotnet developmentSynapseIndia dotnet development
SynapseIndia dotnet development
 
SynapseIndia dotnet client library Development
SynapseIndia dotnet client library DevelopmentSynapseIndia dotnet client library Development
SynapseIndia dotnet client library Development
 
SynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically developmentSynapseIndia creating asp controls programatically development
SynapseIndia creating asp controls programatically development
 

Kürzlich hochgeladen

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 

Kürzlich hochgeladen (20)

Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

Synapseindia object oriented programming in php

  • 1. Object oriented programming in PHP • PHP, like most modern programming languages (C++, Java, Perl, JavaScript, etc.), supports the creation of objects. • Creating an object requires you to first define an object class (containing variables and/or function definitions) and then using the “new” keyword to create an instance of the object class. (Note that the object must be defined before you instantiate it.) <?php // Assume that the "Person" object has been previously defined. . . $x = new Person; // creates an instance of the Person class (*no* quotes) // The object type need not be "hardcoded" into the declaration. $object_type = 'Person'; $y = new $object_type; // equivalent to $y = new Person; $z = new Vehicle('Jaguar','green'); // creating an object and passing // arguments to its constructor ?>
  • 2. Defining (declaring) a class • Use the “class” keyword which includes the class name (case-insensitive, but otherwise following the rules for PHP identifiers). Note: The name “stdClass” is reserved for use by the PHP interpreter. <?php class Person { var $name; function set_name($new_name) { $name = $this -> new_name; } function get_name() { return $this -> name; } } • Use the “$this” variable when accessing properties and functions of the current object. Inside a method this variable contains a reference to the object on which the method was called.
  • 3. Declaring a class (cont.) • Properties and functions can be declared as “public” (accessible outside the object’s scope), “private” (accessible only by methods within the same class), or “protected” (accessible only through the class methods and the class methods of classes inheriting from the class. • Note that unless a property is going to be explicitly declared as public, private, or protected, it need not be declared before being used (like regular PHP variables). <?php class Person { protected $name; protected $age; function set_name($new_name) { $name = $this -> new_name; } function get_name() { return $this -> name; } }
  • 4. Declaring a class (cont.) • Classes can also have their own constants defined (using the “const” keyword), can have their own static properties and functions (using the keyword “static” before “var” or “function”), and can also can constructors and destructors (see below). • Static properties and functions are accessed (see below) using a different format than usual for objects, and static functions cannot access the objects properties (i.e. the variable $this is not defined inside of a static function). <?php class HTMLtable { static function start() { echo "<table> n"; } static function end() { echo "</table> n"; } } HTMLtable::start();
  • 5. Accessing properties and methods • Once you have an object, you access methods and properties (variables) of the object using the -> notation. <?php $me = new Person; $me -> set_name('Russ'); $me -> print_name(); $name = $me -> get_name(); echo $me -> get_name(); $age = 36; $me -> set_age($age); ?>
  • 6. Constructors and destructors • Constructors are methods that are (generally) used to initialize the object’s properties with values as the object is created. Declare a constructor function in an object by writing a function with the name __construct(). <?php class Person { protected $name; protected $age; function __construct($new_name, $new_age) { $this -> name = $new_name; $this -> age = $new_age; } // . . . other functions here . . . } $p = new Person('Bob Jones', 45); $q = new Person('Hamilton Lincoln', 67); ?> • Destructors (defined with a function name of __destructor() ) are called when an object is destroyed, such as when the last reference to an object is removed or the end of the script is reached (the usefulness of destructors in PHP is limited, since, for example dynamic memory allocation isn’t possible in the same way that it is in C/C++).
  • 7. Inheritance • Use the “extends” keyword in the class definition to define a new object that inherits from another. <?php class Employee extends Person { var $salary; function __construct($new_name, $new_age, $new_salary); { $this -> salary = $new_salary; parent::__construct($new_name, $new_age); // call the constructor // of parent object } function update_salary($new_salary) { $this -> salary = $new_salary; } $emp = new Employee('Dave Underwood', 25, 25000); ?>
  • 8. Inheritance (cont.) • The constructor of the parent isn’t called unless the child explicitly references it (as in this previous case). There is no automatic chain of calls to constructors in a sequence of objects defined through inheritance. • You could “hard-code” the call to the parent constructor using the function call “Person::__construct($new_name, $new_age);” but it’s typically better to define it in the manner given using the parent::method() notation. The same manner is used to call the method of a parent that has been overridden by its child. • You can use the “self” keyword to ensure that a method is called on the current class (if a method might be subclassed), in this style self::method(); • To check if an object is of a particular class, you can use the instanceof operator. if ($p instanceof Employee) { // do something here }
  • 9. More on classes • You can also define interfaces for objects (for which any object that uses that interface must provide implementations of certain methods), and you can define abstract classes or methods (that must be overridden by its children). • The keyword “final” can be used to denote a method that cannot be overridden by its children. class Person { var $name; final function get_name() { return $this -> name; } }
  • 10. More on classes (cont.) • There are methods for “introspection” about classes, i.e. the ability of a program to examine an object’s characteristics. For example, the function class_exists() can be used (surprise!) to determine whether a class exists or not. The function get_declared_classes() returns an array of declared classes. $classes = get_declared_classes(); You can also get an array of method names in any of the following (equivalent) manners: $methods = get_class_methods(Person); $methods = get_class_methods('Person'); $class = 'Person'; $methods = get_class_methods($class);
  • 11. More introspection functions • There are a wide variety of introspection functions, several more are listed below. get_class_vars($object); /* gets an associative array that maps property names to values (including inherited properties), but it *only* gets properties that have default values (those initialized with simple constants) */ is_object($object); // returns a boolean value get_class($object); /* returns the class to which an object belongs */ method_exists($object, $method); // returns a boolean value get_object_vars($object); /* returns an associative array mapping properties to values (for those values that are set (i.e. not null) */
  • 12. A word about object methods… • When defining the names of your own object methods, you should generally avoid starting them with a double underscore. Why? • There are some “built-in” or predefined PHP method names that start in this manner, most notably constructors and destructors using the __construct() and __destructor() names. In the future (in new versions of PHP), it’s possible that further methods might be defined that begin with a double underscore. • Other reserved method names include __sleep() and __wakeup() which are used for object serialization and __get() and __set(), which can be defined so that if you try to access an object property that doesn’t exist, these methods give an opportunity to either retrieve a value or set the (default?) value for that property. For example, if a class is used to represent data obtained from a database, you could write __get() and __set() methods that read and write data whenever requested.
  • 13. PHP sessions • By default, HTML and web servers don’t keep track of information entered on a page when the client’s browser opens another page. Thus, doing anything involving the same information across several pages can sometimes be difficult. • Sessions help solve this problem by maintaining data during a user’s visit, and can store data that can be accessed from page to page in your site. • You can use session variables for storing information (this is one way that a “shopping cart” function can work for an online shop, for example). • Servers keep track of users’ sessions by using a session identifier, which is generated by the server when a session starts and is then used by the browser when it requests a page from the server. This session ID can be sent through a cookie (the default behavior) or by passing the session ID in the URL string. • Sessions only store information temporarily, so if you need to preserve information, say, between visits to the same site, you should likely consider a method such as using a cookie or a database to store such information.
  • 14. PHP sessions (cont.) • To start a session, use the function session_start() at the beginning of your PHP script before you store or access any data. For the session to work properly, this function needs to execute before any other header calls or other output is sent to the browser. <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//Www//DTD XHTML 1.0 Transitional//EN" "http://www.abc.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Session example</title> </head> <body> <?php include_once ('object.php'); // Includes definition of the Person class $_SESSION['hello'] = 'Hello world'; echo $_SESSION['hello'] . "<br/><br/>n"; $_SESSION['one'] = 'one'; $_SESSION['two'] = 'two'; $me = new Person("Russ", 36, 2892700); $_SESSION['name'] = $me->get_name(); echo "Testing " . $_SESSION['one'] .", " . $_SESSION['two'] . ", " . $me- >get_number() . " . . .<br/>n"; ?> </body></html> view the output page
  • 15. Using session variables • Once a session variable has been defined, you can access it from other pages. <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//abc//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Session example 2</title> </head> <body> <?php echo "Welcome to a new page ". $_SESSION['name'] "!<br/>n"; echo "Hope you enjoy your stay! <br/>"; ?> <p>Back to regular HTML text... </p> </body> </html> view the output page
  • 16. More on session variables • You need to include a call to the session_start() function for each page on which you want to access the session variables. • A session will end once you quit the browser (unless you’ve set appropriate cookies that will persist), or you can call the session_destroy() function. (Note, however, even after calling the session_destroy() function, session variables are still available to the rest of the currently executing PHP page.) • The function session_unset() removes all session variables. If you want to remove one variable, use the unset($var) function call. • The default timeout for session files is 24 minutes. It’s possible to change this timeout.
  • 17. Deleting all session variables <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//abc//DTD XHTML 1.0 Transitional//EN" "http://www.abc.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.abc.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Session example 3</title> </head> <body> <?php echo "Deleting all session variables using session_unset(); <br/>n"; session_unset(); echo "Now the session variables are gone. <br/>n"; if (isset($_SESSION['name'])) { echo $_SESSION['name'] . "<br/>n"; } else { echo "Session variable is not here."; } ?> </body> </html> view the output page
  • 18. Learning Outcomes • A (very, very brief) introduction to objects in PHP. If you wish to use objects, then many books on PHP include more information, and, of course, much information is available online. • Sessions are useful for persistence of variables across many webpages without the need to submit information via forms.