Nikolay Kostov Telerik Corporation www.telerik.com.

Slides:



Advertisements
Similar presentations
PHP functions What are Functions? A function structure:
Advertisements

OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Python Objects and Classes
Object Oriented Programming in PHP 5
Object-Oriented PHP (1)
Road Map Introduction to object oriented programming. Classes
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Advanced Object-Oriented Programming Features
Scott Grissom, copyright 2004Ch 3: Java Features Slide 1 Why Java? It is object-oriented provides many ready to use classes platform independent modern.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Inheritance and Polymorphism CS351 – Programming Paradigms.
Review of C++ Programming Part II Sheng-Fang Huang.
OOP Languages: Java vs C++
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Pointer Data Type and Pointer Variables
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Chapter 8 More Object Concepts
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
Martin Kruliš This is an Object Oriented system. If we change something, the users object by Martin Kruliš (v1.0)1.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
OOP with PHP Roman Bednarik
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1. Connecting database from PHP 2. Sending query 3. Fetching data 4. Persistent connections 5. Best practices.
Object Oriented Programming in PHP. Topics Quick OOP Review Classes Magic Methods Static Methods Inheritance Exceptions Interfaces Operators Type Hinting.
CSE 425: Object-Oriented Programming I Object-Oriented Programming A design method as well as a programming paradigm –For example, CRC cards, noun-verb.
OOP IN PHP `Object Oriented Programming in any language is the use of objects to represent functional parts of an application and real life entities. For.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
CPSC 252 The Big Three Page 1 The “Big Three” Every class that has data members pointing to dynamically allocated memory must implement these three methods:
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
David Lawrence 7/8/091Intro. to PHP -- David Lawrence.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 15 Inheritance.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
21. PHP Classes To define a class, use the keyword class followed by the name and a block with the properties and method definitions Properties are declared.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Topic: Classes and Objects
Advance OOP in PHP.
Andy Wang Object Oriented Programming in C++ COP 3330
Chapter 11 Developing Object-Oriented PHP PHP Programming with MySQL Revised by A. Philipp – Spring 2010 (Rev SP’11)
Introduction to Classes
Java Programming Language
Object-Oriented Programming in PHP
CISC/CMPE320 - Prof. McLeod
Object-Oriented PHP (1)
Classes and Objects Imran Rashid CTO at ManiWeber Technologies.
SPL – PS3 C++ Classes.
Presentation transcript:

Nikolay Kostov Telerik Corporation

 Classes and objects  Methods and properties  Scope  Inheritance  Static methods and properties  Constants  Abstraction and interfaces

 Overloading  Object Iteration  Object Cloning  Serialization  Namespaces  Autoloading Classes

 The idea of Object Oriented Programming is to move the architecture of an application closer to real world  Classes are types of entities  Objects are single units of a given class  Example – Dog is a class, your dog Lassie is an object of class Dog  Classes have methods and properties  Classes and objects help to create well- structured application

 Declaring of a class in PHP can be done anywhere in the code  Two special methods: constructor and destructor  Executed when creating or destroying new object of this class  Used to initialize or cleanup properties and etc. class Dog { … // declare methods and properties } class Dog { … // declare methods and properties }

 Class definition begins with the class keyword, followed by its name and methods and properties list  Objects of class (instances) are created with the keyword new class A { function foo () { echo "foo here!"; } } $myFirstObject = new A(); $myFirstObject->foo(); // prints out "foo here!"; class A { function foo () { echo "foo here!"; } } $myFirstObject = new A(); $myFirstObject->foo(); // prints out "foo here!"; class name Method name and body Create new object of class A Execute method of this object

 Each class can have only one constructor  All parameters of the creating of the object are passed to the constructor class A { function __construct ($bar) { echo $bar; } function foo () { echo "foo here!"; } } $myFirstObject = new A('test'); // print 'test' class A { function __construct ($bar) { echo $bar; } function foo () { echo "foo here!"; } } $myFirstObject = new A('test'); // print 'test'

 Class can have unlimited number of properties  The $this variable points to the current object – called execution context class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint(); class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint();

 Class can specify default value for a property  Properties can be accessed from the outside world class A { var $bar = 'default value'; … class A { var $bar = 'default value'; … class A { var $bar = 'default value'; …} $obj = new A; echo $obj->bar; class A { var $bar = 'default value'; …} $obj = new A; echo $obj->bar;

 Example of what $this is  Can be used to access methods too class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' $anotherObject = new A('foo'); $anotherObject ->myPrint(); // prints 'foo'; class A { var $bar; function __construct ($bar) { $this->bar = $bar; } function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' $anotherObject = new A('foo'); $anotherObject ->myPrint(); // prints 'foo';

 Each class can have only one destructor  Must be public  Destructors are automatically called when script is shutting down class A { function __construct ($name) { $this->fp = fopen ($name, 'r'); } function __destruct () { fclose($this->fp);}} $myFirstObject = new A('test'); class A { function __construct ($name) { $this->fp = fopen ($name, 'r'); } function __destruct () { fclose($this->fp);}} $myFirstObject = new A('test');

 Each method and property has a scope  It defines who can access it  Three levels – public, protected, private  Private can be access only by the object itself  Protected can be accessed by descendant classes (see inheritance)  Public can be accessed from the outside world  Level is added before function keyword or instead of var  var is old style (PHP 4) equivalent to public  Constructors always need to be public

class A { private $bar; public function __construct ($bar) { $this->bar = $bar; } public function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' // this will not work: echo $myFirstObject->bar; class A { private $bar; public function __construct ($bar) { $this->bar = $bar; } public function myPrint () { echo $this->bar; }} $myFirstObject = new A('test'); $myFirstObject->myPrint(); // prints 'test' // this will not work: echo $myFirstObject->bar; The $bar variable is private so only the object can access it The myPrint method is public, so everyone can call it

 A class can inherit (extend) another class  It inherits all its methods and properties class A { public $bar = 'test'; public function example () { … } } class B extends A { … } $obj = new B(); echo $obj->bar; //prints 'test' //calls the A-class function $obj->example(); class A { public $bar = 'test'; public function example () { … } } class B extends A { … } $obj = new B(); echo $obj->bar; //prints 'test' //calls the A-class function $obj->example();

 Method or property, declared as protected can be accessed in classes that inherit it, but cannot be accessed from the outside world class A { protected $bar = 'test'; } class B extends A { public function foo () { // this is allowed $this->bar = 'I see it'; } } $obj = new B(); echo $obj->bar; //not allowed class A { protected $bar = 'test'; } class B extends A { public function foo () { // this is allowed $this->bar = 'I see it'; } } $obj = new B(); echo $obj->bar; //not allowed

 When a class inherits another, it can declare methods that override parent class methods  Method names are the same  Parameters may differ class A { public foo() { … } } class B extends A { public foo() { … } } class A { public foo() { … } } class B extends A { public foo() { … } }

class A { public foo() { echo 'called from A'; }} class B extends A { public foo() { echo 'called from B'; }} $obj1 = new A(); $obj2 = new B(); $obj1->foo(); // executes A's methods $obj2->foo(); // executes B's methods class A { public foo() { echo 'called from A'; }} class B extends A { public foo() { echo 'called from B'; }} $obj1 = new A(); $obj2 = new B(); $obj1->foo(); // executes A's methods $obj2->foo(); // executes B's methods

 As -> is used to access object's methods and properties, the :: (double colon) is used to change scope  Scope Resolution Operator  parent:: can be used to access parent's class overridden methods  Example: call parent's constructor in the child one

 Example of calling parent constructor class A { protected $variable; public __construct() { $this->variable = 'test'; }} class B extends A { public __construct() { parent::__construct(); echo $this->variable; }} $obj1 = new B(); // prints 'test'; class A { protected $variable; public __construct() { $this->variable = 'test'; }} class B extends A { public __construct() { parent::__construct(); echo $this->variable; }} $obj1 = new B(); // prints 'test';

 Defining method or property as 'static' makes them accessible without needing an instantiation of a class  Accessed with the double-colon (::) operator instead of the member (->) operator  $this is not available in static methods  Static properties and methods can also have scope defined – public, private or protected

 Example of static method and property  Class can access statics with the self keyword  Outside world accesses statics with the class name class A { public static $myVariable; public static function myPrint() { echo self::$myVariable; } } A::$myVariable = 'test'; A::myPrint(); class A { public static $myVariable; public static function myPrint() { echo self::$myVariable; } } A::$myVariable = 'test'; A::myPrint();

 Constants in PHP usually are declared with the define function  Constants can be defined in class  Differ from normal variables – no need for $ symbol to declare and access  Declared with the const keyword  Value must be supplied with the declaration  Accessed with scope operator (::)  Can be overridden by child classes  Value must be constant expression, not a variable, class member, result of operation or function call

 Example of a class constant class A { const myConstant = 'value'; public function showConstant() { echo self::myConstant; } } echo A::myConstant; $obj = new A(); $obj->showConstant(); class A { const myConstant = 'value'; public function showConstant() { echo self::myConstant; } } echo A::myConstant; $obj = new A(); $obj->showConstant();

 Classes, defined as abstract, cannot have instances (cannot create object of this class)  Abstract class must have at least one abstract method  Abstract methods do not have implementation (body) in the class  Only signature  The class must be inherited  The child class must implement all abstract methods  Cannot increase visibility

abstract class AbstractClass { abstract protected function getValue(); abstract public function getValue2($prefix); public function printOut () { echo $this->getValue(); } } class Class1 extends AbstractClass { protected function getValue (){ return "Class1"; } public function getValue2($prefix) { return $prefix."NAC1"; } } abstract class AbstractClass { abstract protected function getValue(); abstract public function getValue2($prefix); public function printOut () { echo $this->getValue(); } } class Class1 extends AbstractClass { protected function getValue (){ return "Class1"; } public function getValue2($prefix) { return $prefix."NAC1"; } }

// continue from previous slide class Class2 extends AbstractClass { protected function getValue (){ return "Class2"; } public function getValue2($prefix) { return $prefix."NAC2"; } } $class1 = new Class1(); $class1->printOut(); // "Class1"; echo $class1->getValue2('FOO'); // FOONAC1 $class2 = new Class2(); $class2->printOut(); // "Class2"; echo $class2->getValue2('FOO'); //FOONAC2 // continue from previous slide class Class2 extends AbstractClass { protected function getValue (){ return "Class2"; } public function getValue2($prefix) { return $prefix."NAC2"; } } $class1 = new Class1(); $class1->printOut(); // "Class1"; echo $class1->getValue2('FOO'); // FOONAC1 $class2 = new Class2(); $class2->printOut(); // "Class2"; echo $class2->getValue2('FOO'); //FOONAC2

 Object interfaces allow you to specify what methods a child class must implement  Declared with the interface keyword  Similar to abstract class  Interface can have only public methods  No method in interface can have implementation  Interfaces are inherited with the implements keyword (instead of extends )  One class may implement multiple interfaces, if they do not have methods with same names

interface iTemplate { public function set ($name, $value); public function set ($name, $value); public function getHTML($template); } public function getHTML($template); } class Template implements iTemplate { private $vars = array(); private $vars = array(); public function set ($name, $value) { public function set ($name, $value) { $this->vars[$name] = $value; $this->vars[$name] = $value; } public function getHTML($template) { public function getHTML($template) { foreach($this->vars as $name=>$value) { foreach($this->vars as $name=>$value) { $template = str_replace( $template = str_replace( '{'.$name.'}', $value, $template); } return $template; } } '{'.$name.'}', $value, $template); } return $template; } } interface iTemplate { public function set ($name, $value); public function set ($name, $value); public function getHTML($template); } public function getHTML($template); } class Template implements iTemplate { private $vars = array(); private $vars = array(); public function set ($name, $value) { public function set ($name, $value) { $this->vars[$name] = $value; $this->vars[$name] = $value; } public function getHTML($template) { public function getHTML($template) { foreach($this->vars as $name=>$value) { foreach($this->vars as $name=>$value) { $template = str_replace( $template = str_replace( '{'.$name.'}', $value, $template); } return $template; } } '{'.$name.'}', $value, $template); } return $template; } }

 Overloading in PHP provides the means to dynamically create members and methods via set of "magical" methods  Invoked with interacting with members or methods that have not been declared or are not visible in the current scope  All of the magic methods must be declared as public  None of the magic functions can be called with arguments, passed by reference

 All overloading methods are invoked when accessing variable or method that is not declared or is inaccessible  __set($name, $value) – when writing  __get ($name) –when reading  __isset ($name) – when calling isset() function  __unset ($name) – when calling unset() function

 __call ($name, $arguments) - when calling a method  __callStatic ($name, $arguments) – when calling a method in a static context  Added after PHP 5.3  Must always be declared as static  PHP "overloading" is a lot different from most languages "overloading"  Usually it means the ability to declare two methods with different sets of parameters but same names

 PHP provides a way for object to be iterated trough as a list of items (array)  foreach can be used  By default iterates all visible properties

class A { public $var1 = 1; public $var2 = 2; protected $var3 = 3; private $var4 = 4; function printIteration () { foreach ($this as $key=>$val) echo "$key : $val\n"; } } $obj = new A(); // this prints only the public properties foreach ($obj as $key=>$val) echo "$key : $val \n"; // this prints protected and private too $obj->printIteration (); class A { public $var1 = 1; public $var2 = 2; protected $var3 = 3; private $var4 = 4; function printIteration () { foreach ($this as $key=>$val) echo "$key : $val\n"; } } $obj = new A(); // this prints only the public properties foreach ($obj as $key=>$val) echo "$key : $val \n"; // this prints protected and private too $obj->printIteration ();

 To take object iteration a step further, you can implement one of the PHP interfaces  Provided by the Standard PHP Library  Allows the objects to decide what to show and what not  Some provided interfaces:  Iterator – very long to implement but provides dull features  IteratorAggregate – simple version of Iterator interface  ArrayIterator, DirectoryIterator, etc.

 An object can be cloned with the clone keyword  This will create new independent object  Creating a copy of an object with fully replicated properties is not always the wanted behavior $obj1 = new A(); $obj2 = clone $obj1; $obj1 = new A(); $obj2 = clone $obj1;

 A class can implement the magic method __clone which is called for the newly created object  Called "clone constructor"  Allows necessary changes to be done on the newly created object  Example: Object holding reference to resource – the new object must have new references, instead of copies  Example: Object holding reference to another object that must not be copied

class A { private $fileName; private $fp = null; public function open ($file) { $this->fileName = $file; $this->fp = fopen ($file, 'r'); } public function close () { if ($this->fp) { fclose($this->fp); $this->fp = null; }} public function __clone () { // reopen the file for the new object if ($this->fp) $this->fp= fopen($this->file, 'r'); } } class A { private $fileName; private $fp = null; public function open ($file) { $this->fileName = $file; $this->fp = fopen ($file, 'r'); } public function close () { if ($this->fp) { fclose($this->fp); $this->fp = null; }} public function __clone () { // reopen the file for the new object if ($this->fp) $this->fp= fopen($this->file, 'r'); } }

 Serializing is the process of transforming an object into a string, that can be stored  This string can be used to restore the object  Useful for storing objects in session data  Saves only properties values and class names – no methods  PHP provides the serialize and unserialize functions

 serialize ($object) – returns string, representing the object  unserialize ($string) – returns new object, that is restored from the serialized string  unserialize requires the class to be defined before calling it

class A { public $var; public function myPrint () { echo $this->var; } } $obj = new A; $obj->var = 10; $data = serialize ($obj); // store $data in a file file_put_contents ('data.dat', $data); // … // in a new page: $data = file_get_contents ('data.dat'); $obj = unserialize ($data); $obj->myPrint (); // prints 10 class A { public $var; public function myPrint () { echo $this->var; } } $obj = new A; $obj->var = 10; $data = serialize ($obj); // store $data in a file file_put_contents ('data.dat', $data); // … // in a new page: $data = file_get_contents ('data.dat'); $obj = unserialize ($data); $obj->myPrint (); // prints 10

 Before serializing and after unserializing PHP checks if the class has the magic methods __sleep and __wakeup  __sleep allows the class to commit pending data, cleanup or define what needs to be stored if the object is very large  Should return array with names of properties to be stored  __wakeup allows the class to restore connections or other re-initialization

class Connection { protected $link; private $server, $user, $pass, $db; public function __construct($server, $user, $pass, $db) { $this->server = $server; $this->user = $user; $this->pass = $pass; $this->db = $db; $this->connect(); } private function connect () { $this->link = mysql_connect ( $this->server, $this->user, $this->pass); mysql_select_db($this->db, $this->link); } // continues on next slide class Connection { protected $link; private $server, $user, $pass, $db; public function __construct($server, $user, $pass, $db) { $this->server = $server; $this->user = $user; $this->pass = $pass; $this->db = $db; $this->connect(); } private function connect () { $this->link = mysql_connect ( $this->server, $this->user, $this->pass); mysql_select_db($this->db, $this->link); } // continues on next slide

// continues from previous slide public function __sleep () { // skip serializing $link return array ('server', 'user', 'pass', 'db'); } public function __wakeup () { public function __wakeup () { $this->connect(); } } // continues from previous slide public function __sleep () { // skip serializing $link return array ('server', 'user', 'pass', 'db'); } public function __wakeup () { public function __wakeup () { $this->connect(); } }

 Namespaces in PHP are designed to resolve scope problems in large PHP libraries  Simplify development in object oriented environment  Clears the code – no long classes names  In PHP all classes declarations are global  Namespaces allow to have two classes with same name  Old approach was adding prefixes to class names (Like the mysql_* functions)  Available since PHP 5.3

 Namespaces are declared with the namespace keyword  Should be always in the beginning of the file  Namespace can contain classes, constants, functions but no free code <? namespace Project; class MyTemplate { … } function print_headers () { … } …?><? namespace Project; class MyTemplate { … } function print_headers () { … } …?>

 Classes, function and etc. in a namespace are automatically prefixed with the name of the namespace  So in the example we would use Project::MyTemplate to access the class  Constants in namespaces are defined with const keyword, not with define

// file Project.php namespace Project; // declare base classes and etc. … // file project/db.php; namespace Project::DB; // declare DB interface for work with database … // file project/db/mysql.php namespace Project::DB::MySQL; // implement the DB interface for mysql … // file project/db/oracle.php Namespace Project::DB::Oracle; // implement the DB interface for Oracle … // somewhere in the project require "project/db/mysql.php"; $a = new Project::DB::MySQL::Connection(); Project::DB::MySQL::connect(); // file Project.php namespace Project; // declare base classes and etc. … // file project/db.php; namespace Project::DB; // declare DB interface for work with database … // file project/db/mysql.php namespace Project::DB::MySQL; // implement the DB interface for mysql … // file project/db/oracle.php Namespace Project::DB::Oracle; // implement the DB interface for Oracle … // somewhere in the project require "project/db/mysql.php"; $a = new Project::DB::MySQL::Connection(); Project::DB::MySQL::connect();

 The use operator allows aliasing namespaces names  If new name is not specified the namespace is imported in the current context (global namespace)  Even if aliased, every class and function can be accessed at any time by full name use Project::DB::MySQL as DBLink; $x = new DBLink::Connection(); DBLink::connect(); use Project::DB::MySQL as DBLink; $x = new DBLink::Connection(); DBLink::connect(); use Project::DB::MySQL; $x = new MySQL::Connection(); MySQL::connect(); use Project::DB::MySQL; $x = new MySQL::Connection(); MySQL::connect();

 By default PHP works in the global namespace  All the project is executed there  Method from the global namespace can be referred to with empty scope operator namespace Project::Files; // this is the Project::Files::fopen function function fopen (…) { … $f = ::fopen (…); // calls global fopen … } namespace Project::Files; // this is the Project::Files::fopen function function fopen (…) { … $f = ::fopen (…); // calls global fopen … }

 Usually every class is declared in separate file  In big object oriented projects on every page you may have to include dozens of files  You can define __autoload function that is called when trying to access class that is not defined  It can include the necessary file for the class

 Exceptions, thrown in __autoload cannot be caught and result in fatal error <? function __autoload ($class_name) { $name = "includes/".$class_name.".inc.php"; if (file_exists ($name)) include $name; else echo 'Class not found'; } ?><? function __autoload ($class_name) { $name = "includes/".$class_name.".inc.php"; if (file_exists ($name)) include $name; else echo 'Class not found'; } ?>

 Example: class A { public static function whoami () { echo __CLASS__; } public static function test () { self::whoami(); } } class B extends A { public static function whoami () { echo __CLASS__; } } B::test(); // outputs 'A' ?! class A { public static function whoami () { echo __CLASS__; } public static function test () { self::whoami(); } } class B extends A { public static function whoami () { echo __CLASS__; } } B::test(); // outputs 'A' ?!

 PHP 5.3 introduces the late static binding which allows to reference the called class in context of static  In practice – this adds static:: scope  So if in the above example we use static::whoami() in the test() method body we get output 'B'

Questions?

1. Define class Student that holds information about students: full name, course, specialty, university, , phone. 2. Define constructor for the class Student that takes full name as parameter. 3. Add a method in the class Student for displaying all information about the student. 4. Create two students and print their information. 5. Create an interface IAnimal that represents an animal from the real world. Define the method talk() that prints the specific scream of the animal ("jaff" for dogs, "muaw" for cats, etc.).

6. Create an abstract class Cat that has Name and implements the interface IAnimal and introduces abstract method printInfo(). 7. Inherit from the base abstract class Cat and create subclasses Kitten and Tomcat. These classes should fully implement the IAnimal interface and define an implementation for the abstract methods from the class Cat. 8. Create class Dog that implements IAnimal. 9. Write a class TestAnimals that creates an array of animals: Tomcat, Kitten, Dog and calls their methods through IAnimal interface to ensure the classes are implemented correctly.

Exercises (3) 10. We are given a school. In the school there are classes of students. Each class has a set of teachers. Each teacher teaches a set of disciplines. Students have name and unique class number. Classes have unique text identifier. Teachers have name and title. Disciplines have name, number of lectures and number of exercises. Define classes for the school ( School, Class, Student, Teacher, Discipline ). Keep the member fields private. Add constructors and accessor methods. Write a testing class to construct and print a sample school.

Exercises (4) 11. We need to implement a message board where visitor can read all messages, add new messages, edit and delete existing messages. Implement this as a PHP application by following the steps below:  Create a MySQL database Messages and define in it a table messages(id, author, subject, msgDate, msgBody).  Write a class Message which will hold a single message with its id, author, subject, msgDate and msgBody. Put this class in the file message.class.php.

Exercises (5)  Write a class DBUtils which will be responsible for database access for the entire application. Put this class in the file db-utils.class.php. Implement the following methods:  dbConnect() – connects to the MySQL database and selects Messages database  getAllMessages() – returns an array of Message objects containing all messages from the database  addMessage($msg) – inserts a message given as Message object to the database  updateMessage($msg) – updates a message given as Message object in the database  deleteMessageById($msg_id) - deletes given message specified by its primary key

Exercises (6)  Write a PHP script index.php which displays all messages in a table.  Implement a form for adding a message as separate script add-message.php.  Implement deleting of a message by clicking a hyperlink in the corresponding row in the table. Implement it as separate script delete.php.  Implement editing of a message by clicking on a hyperlink in the corresponding row in a table. Implement it as separate script edit-message.php.