OOP with PHP
E N D
Presentation Transcript
Roman Bednarik rbednari@cs.joensuu.fi OOP with PHP
OOP with PHPlecture outline • What is PHP • Why use OOP with PHP • OOP with PHP • Advanced topics on OOP and PHP
OOP with PHPwhat is PHP? - development • PHP = PHP Hypertext Preprocessor • Originally a collection of scripts • Developed as open source • Major revision in 2001 • In 2001 ~ 5 millions of domains using PHP • In Oct 2002 ~ 9 millions ! • Nowadays in version PHP4 (PHP 4.3RC2) – this lecture • PHP5 in development
OOP with PHPwhat is PHP? - usage • Server side scripting generating (not only) HTML • Strong association with the Apache server and MySQL • Many OS covered • Great number of additional modules
OOP with PHPwhat is PHP? - characteristics • Interpreted • Loosely type checking • Overloading not supported • Enables references • Case sensitive • Variable variable names • Associative arrays • Serialization of objects into the stream
OOP with PHPwhat is PHP? - example PHP source (example.php) <html> <body> <?php $A = 1; $B = 2; $C = $A + $B; echo “Result of $A+$B=”.$C; echo “<BR>\n”; echo “Hello world!”; ?> </body> </html> HTML output <html> <body> Result of 1+2 =3<BR> Hello world! </body> </html> Browser view Result of 1+2 =3 Hello world!
OOP with PHPlecture outline • What is PHP • Why use OOP with PHP • OOP with PHP • Advanced topics on OOP and PHP
OOP with PHPwhy OOP in PHP • Common OOP approach advantages • Modularity • Less code • Reusability • Robustness • Handling large projects, easy to maintain • Classes usually reflect database schema • PHP is not inherently OOP language!
OOP with PHPwhy OOP in PHP – examples • Online shops • Banking systems • News services • Editors' systems • Home pages • => use OOP to separate the functionality from layout
OOP with PHPlecture outline • What is PHP • Why use OOP with PHP • OOP with PHP (or PHP with OOP?) • Advanced topics on OOP and PHP
OOP with PHPcharacteristics • PHP fulfills: • Abstract data types • Information hiding • Inheritance • Polymorphism • PHP fails: • Later on .. • Almost all can be resolved by some of the 'workarounds'
<?php class FirstClass { var $x; // data member – no ways of specifying private/protected function setX ($a) { $this->x = $a; } function getX () { return $this->x; } function printX(){ echo $this->x;} } // class $instanceA = new FirstClass; ?> OOP with PHPcase class
OOP with PHPAbstract data types • Both we have in PHP classes: • Data : integer, string, array, associative array, object • In PHP: no data protection, public is default • Methods: defined as a member functions e.g: function setData1 ($aData1=”default”) { $this -> Data1 = $aData1; }
OOP with PHPInformation hiding – encapsulation • Good practice is to use set and get methods to access the member structures • C++, Java, Ada etc. allow protected/private/public • PHP only public by default
OOP with PHPInheritance • In PHP using keyword extends <?php class SecondClass extends FirstClass{ var $Y; function setY ($a) { if ( getX()>0) $this->Y = $a; // getX inherited else $this->Y = 0; } } ?> • Multiple inheritance is not supported
OOP with PHPPolymorphism • All class member functions are virtual by the definition class A { function draw() { echo "1"; } // not needed function boo() { $this->draw(); } } class B extends A { function draw() { echo "drawing B"; } } $b = new B(); $b->boo(); // outputs “drawing B”
OOP with PHPconstructors • All initialization has to be done in constructor • No constructor chaining! => when an object as an instance of derived class is created, only it's constructor is called. If does not exist, parental constructor is called. • Solution: • Explicit constructor call • parent:: name_of_parent_class(); • No destructors in PHP – automatic garbage collection
OOP with PHPabstract classes • Abstract class is not instantiable • No standard way in PHP • Solution: • Call die in the constructor and methods • if the method is not overridden in a derived class the error occurs
OOP with PHPstatic variables • One instance for all objects of the class • No standard way in PHP • Workarounds: • Global variables: giving a reference of global variable in each constructor call (creation) • e.g.:
OOP with PHPstatic variables $GLOBALS['_transient']['static']['test']->v1 = 1; // global storage class Test { function Test() { // constructor $this->v1 = & $GLOBALS['_transient']['static']['test']->v1; // link a new variable } function printAndIncrease() { echo "$this->v1 <br>"; $this->v1++; } var $v1; } $test1 = new Test(); // invokes constructor $test1->printAndIncrease(); $test2 = new Test(); $test2->printAndIncrease();
OOP with PHPPHP fails on • No templates • No private/protected members • No casting from one class to another • No static class variables • No interfaces • No exceptions • => many to be resolved in PHP5
OOP with PHP <?php class Element{ //basic class for all elements function Element($caption=""){ $this->Setup($caption); } function Setup($caption) { $this->caption = $caption; } function Set(){ //virtual methods } function Get(){ } function GetCaption(){ return $this->caption; } function Print_(){} } ?>
OOP with PHP <?php include_once("class.element.php"); class Button extends Element { //inheritance function Button($caption="",$action=""){ $this->Setup($caption,$action); } function Setup($caption,$action) { $this->caption = $caption; $this->action = $action; } function Print_() { echo "<INPUT TYPE=button "; if ($this->caption) echo "VALUE=\"$this->caption\" "; if ($this->action) echo "OnClick=\"$this->action\" "; echo ">\n"; } } ?>
OOP with PHP <?php include_once("class.element.php"); include_once("class.button.php"); class Page{ var $reload; function Page($caption="",$obj){ $this->Setup($caption,$obj); //add the properties and elements common to all pages $this->reload = new Button("Reload","document.location.reload();"); } function Setup($caption, $obj) { $this->caption = $caption; $this->obj = $obj; } function GetCaptions() { for ($i=0; $i< count($this->obj); $i++) { echo $this->obj[$i]->GetCaption(); echo "<BR>";} }
OOP with PHP function print_(){ echo "<HTML>\n <HEAD>\n <TITLE>"; if ($this->caption) echo "$this->caption"; echo " </TITLE>\n"; echo " </HEAD>\n"; echo " <BODY>\n"; $this->reload->Print_(); for ($i=0; $i< count($this->obj); $i++) { //invoke Print_() for all //elements on page $this->obj[$i]->Print_(); echo "<BR>"; } echo " </BODY>\n"; echo "</HTML>\n"; } } ?>
OOP with PHPhttp://cs.joensuu.fi/pages/bednarik/OOP/example.php <?php include("class.element.php");include("class.button.php"); include("class.table.php");include("class.page.php"); $tab= new Table(); $tab->Setup("My table 10x3",10,3); $tab2= $tab; $tab2->Setup("My table 2 3x3",3,3); $but = new Button("Click me","alert('Hello');"); $obs[0] = $tab; $obs[1] = $tab2; $obs[2] = $but; $page= new Page("Object Page",$obs); $page->Print_(); $page->GetCaptions(); ?>
OOP with PHPlecture outline • What is PHP • Why use OOP with PHP • OOP with PHP • Advanced topics on OOP and PHP
OOP with PHP Generic function for setting the member variables function Set ($varname, $value) { $this->$varname = $value; } $instance->Set ('size','5');
OOP with PHPSerializing the objects • Partially overcomes the need for a persistent object • !!Saves only data members, not methods! (PHP4 is exception) <?php $myCart = new ShoppingCart(); $stream1 = serialize($myCart); // and store to file or db ... ... // retreive from file/db after a year.. $myLaterCart = unserialize($stream1); ?> • Not recommended to use!
OOP with PHPOverloading in PHP <?php class ShoppingCart{ function ShoppingCart(){ $to_call="ShoppingCart".func_num_args(); $args = func_get_args(); // return an array of arguments $args = implode(':',$args); $args = str_replace(“:”, “,”, $args); $run = “\$this->$to_call ($args);”; // variable variable eval ($run); } function ShoppingCart1($x=”2”) { code1();} function ShoppingCart2($x=”2”,$y=”3”) { code2();} } ?>
OOP with PHPSerializing the objects (cont.) • Stream is a string with defined format • One might try to investigate it: $myCart = new ShoppingCart(); $stream1 = serialize($myCart); $hocus = explode(':',$stream1); // split $stream1 by : into array e.g. $classname = str_replace( “\””, '' ,$hocus[2] ); // takes away the “
USE OOP! Thank you