Beruflich Dokumente
Kultur Dokumente
Nikolay Kostov
Technical Trainer
http://nikolay.it
Telerik Software Academy
academy.telerik.com
Summary
Classes and objects
Methods and properties
Scope
Inheritance
Constants
Object Iteration
Object Cloning
Serialization
Namespaces
Autoloading Classes
Classes and Objects
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
Classes in PHP
Declaring of a class
in PHP can be done
anywhere in the code
class Dog {
… // declare methods and properties
}
Two special methods: constructor and
destructor
Executed when creating or destroying new object
of this class
Used to initialize or cleanup properties and etc.
Classes in PHP
Class definition begins with the class
keyword, followed by its name and methods
andclass name Method
properties list name
and body
class A {
function foo () {
echo Create new object
"foo here!";
} of class A
}
$myFirstObject = new A();
$myFirstObject->foo(); // prints out "foo
here!";
Execute method of
this object
Objects of class (instances) are created with the
keyword new
Constructors
Each class can have only one constructor
class A {
function __construct ($bar) {
echo $bar;
}
function foo () {
echo "foo here!";
}
}
$myFirstObject = new A('test');
// print 'test'
class A {
public foo() { … }
}
class B extends A {
public foo() { … }
}
Overriding Example
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
Accessing Parent Class
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
Accessing Parent Class
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';
The static Keyword
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
The static Keyword
Example of static method and property
class A {
public static $myVariable;
public static function myPrint() {
echo self::$myVariable;
}
}
A::$myVariable = 'test';
A::myPrint();
class A {
const myConstant = 'value';
echo A::myConstant;
$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
Serializing Methods
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
__sleep and __wakeup
class Connection {
protected $link;
private $server, $user, $pass, $db;
<?
namespace Project;
class MyTemplate { … }
function print_headers () { … }
…
?>
Namespace can contain classes, constants,
functions but no free code
Namespaces
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
Namespaces – Example
// 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();
Using Namespaces
The use operator allows aliasing namespaces
names
use Project::DB::MySQL as DBLink;
$x = new DBLink::Connection();
DBLink::connect();
курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge
курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн
уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET
http://academy.telerik.com
програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезания
курсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране
free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране
безплатен курс "Качествен програмен код"
безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
Exercises
1. Define class Student that holds information about
students: full name, course, specialty, university, email,
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.).
Exercises (2)
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.
Free Trainings @ Telerik Academy
“PHP & MySQL Web Design" course
academy.telerik.com/.../php-school-
academy-meeting
Telerik Software Academy
academy.telerik.com
Telerik Academy @ Facebook
facebook.com/TelerikAcademy
Telerik Software Academy Forums
forums.academy.telerik.com