Object Oriented Concepts In PHP5 (Part 2)

1 comments

1.DESTRUCTORS
Destructor functions
are the opposite of constructors. They are called when the object is being destroyed (for example, when there are no more references to the object). As PHP makes sure all resources are freed at the end of each request, the importance of destructors is limited. However, they can still be useful for performing certain actions, such as flushing a resource or logging information on object destruction. There are two situations where your destructor might be called: during your script’s execution when all references to an object are destroyed, or when the end of the script is reached and PHP.ends the request. The latter situation is delicate because you are relying on
some objects that might already have had their destructors called and are not accessible anymore. So, use it with care, and don’t rely on other objects in your destructors.
Defining a destructor is as simple as adding a __destruct() method to your class:
class MyClass {
function __destruct()
{
print "An object of type MyClass is being destroyed\n";
}
}
$obj = new MyClass();
$obj = NULL;

This script prints
An object of type MyClass is being destroyed


In this example, when
$obj = NULL;
is reached, the only handle to the object is destroyed, and therefore the destructor is called, and the object itself is destroyed. Even without the last line, the destructor would be called, but it would be at the end of the request during the execution engine’s shutdown.


2. ACCESSING METHODS AND PROPERTIES USING THE $this VARIABLE
During the execution of an object’s method, a special variable called $this is automatically defined, which denotes a reference to the object itself. By using this variable and the -> notation, the object’s methods and properties can be further referenced. For example, you can access the $name property by using $this->name (note that you don’t use a $ before the name of the property). An object’s methods can be accessed in the same way; for example, from inside one of person’s methods, you could call getName() by writing $this->getName().

2.1 A public, protected, and private Properties
A key paradigm in OOP is encapsulation and access protection of object properties
(also referred to as member variables). Most common OO languages have three main access restriction keywords: public, protected, and private.When defining a class member in the class definition, the developer
needs to specify one of these three access modifiers before declaring the member
itself. In case you are familiar with PHP 3 or 4’s object model, all class
members were defined with the var keyword, which is equivalent to public in PHP 5. var has been kept for backward compatibility, but it is deprecated, thus, you are encouraged to convert your scripts to the new keywords:
class MyClass {
public $publicMember = "Public member";
protected $protectedMember = "Protected member";
private $privateMember = "Private member";
function myMethod(){
// ...
}
}
$obj = new MyClass();
This example will be built upon to demonstrate the use of these access
modifiers.First, the more boring definitions of each access modifier:
private:Private members are similar to protected members because they can be accessed only from within an object’s method. However, they are also inaccessible from a derived object’s methods. Because private properties aren’t visible from inheriting classes, two related classes may declare the same private properties. Each class will see its own private copy, which are unrelated.
protected:Protected members can be accessed only from within an object’s method—for example, $this->protectedMember. If another class inherits a protected member, the same rules apply, and it can be accessed from within the derived object’s methods via the special $this variable.
public:Public members can be accessed both from outside an object by using $obj->publicMember and by accessing it from inside the myMethod method via the special $this variable (for example, $this->publicMember). If another class inherits a public member, the same rules apply, and it can be accessed both from outside the derived class’s objects and from within its methods.

Usually, you would use public for members you want to be accessible
from outside the object’s scope (i.e., its methods), and private for members who
are internal to the object’s logic. Use protected for members who are internal
to the object’s logic, but where it might make sense for inheriting classes to
override them:

class MyDbConnectionClass {
public $queryResult;
protected $dbHostname = "localhost";
private $connectionHandle;
// ...
}
class MyFooDotComDbConnectionClass extends MyDbConnectionClass {
protected $dbHostname = "foo.com";
}

This incomplete example shows typical use of each of the three access
modifiers. This class manages a database connection including queries made
to the database:

☞ The connection handle to the database is held in a private member,because it is used by the class’s internal logic and shouldn’t be accessible to the user of this class.
☞ In this example, the database hostname isn’t exposed to the user of theclass MyDbConnectionClass. To override it, the developer may inherit from the initial class and change the value.
☞ The query result itself should be accessible to the developer and has, therefore, been declared as public.

Note that access modifiers are designed so that classes (or more specifically,
their interfaces to the outer world) always keep an is-a relationship during
inheritance. Therefore, if a parent declares a member as public, the
inheriting child must also declare it as public. Otherwise, the child would not
have an is-a relationship with the parent, which means that anything you can
do with the parent can also be done with the child.

2.2 public, protected, and private Methods

Access modifiers may also be used in conjunction with object methods, and the rules are the same:
☞ public methods can be called from any scope.
☞ protected methods can only be called from within one of its class methods or from within an inheriting class.

☞ private methods can only be called from within one of its class methods and not from an inheriting class. As with properties, private methods may be redeclared by inheriting classes. Each class will see its own version of the method:
class MyDbConnectionClass {
public function connect()
{
$conn = $this->createDbConnection();
$this->setDbConnection($conn);
return $conn;
}
protected function createDbConnection()
{
return mysql_connect("localhost");
}
private function setDbConnection($conn)
{
$this->dbConnection = $conn;
}
private $dbConnection;
}
class MyFooDotComDbConnectionClass extends MyDbConnectionClass {
protected function createDbConnection()
{
return mysql_connect("foo.com");
}
}

This skeleton code example could be used for a database connection class. The connect() method is meant to be called by outside code. The createDbConnection() method is an internal method but enables you to inherit from the class and change it; thus, it is marked as protected. The setDbConnection() method is completely internal to the class and is therefore marked as private.

2.3 Static Properties

As you know by now, classes can declare properties. Each instance of the class (i.e., object) has its own copy of these properties. However, a class can also contain static properties. Unlike regular properties, these belong to the class itself and not to any instance of it. Therefore, they are often called class properties as opposed to object or instance properties. You can also think of static properties as global variables that sit inside a class but are accessible from anywhere via the class.
Static properties are defined by using the static keyword:
class MyClass {
static $myStaticVariable;
static $myInitializedStaticVariable = 0;
}
To access static properties, you have to qualify the property name with the class it sits in
MyClass::$myInitializedStaticVariable++;
print MyClass::$myInitializedStaticVariable;
This example prints the number 1.
If you’re accessing the member from inside one of the class methods, you may also refer to the property by prefixing it with the special class name self, which is short for the class to which the method belongs:
class MyClass {
static $myInitializedStaticVariable = 0;
function myMethod()
{
print self::$myInitializedStaticVariable;
}
}
$obj = new MyClass();
$obj->myMethod();
This example prints the number 0.
You are probably asking yourself if this whole static business is really useful.
One example of using it is to assign a unique id to all instances of a class:
class MyUniqueIdClass {
static $idCounter = 0;
public $uniqueId;
function __construct()
{
self::$idCounter++;
$this->uniqueId = self::$idCounter;

}
}
$obj1 = new MyUniqueIdClass();
print $obj1->uniqueId . "\n";
$obj2 = new MyUniqueIdClass();
print $obj2->uniqueId . "\n";
This prints
1
2
The first object’s $uniqueId property variable equals 1 and the latter object equals 2.

2.4 Static Methods

Similar to static properties, PHP supports declaring methods as static. What this means is that your static methods are part of the class and are not bound to any specific object instance and its properties. Therefore, $this isn’t accessible in these methods, but the class itself is by using self to access it. Because static methods aren’t bound to any specific object, you can call them without
creating an object instance by using the class_name::method() syntax. You may also call them from an object instance using $this->method(), but $this won’t be defined in the called method. For clarity, you should use self::method()
instead of $this->method().
Here’s an example:
class PrettyPrinter {
static function printHelloWorld()
{
print "Hello, World";
self::printNewline();
}
static function printNewline()
{
print "\n";
}
}
PrettyPrinter::printHelloWorld();

The example prints the string "Hello, World" followed by a newline. Although it is a useless example, you can see that printHelloWorld() can be called on the class without creating an object instance using the class name, and the static method itself can call another static method of the class print- Newline() using the self:: notation. You may call a parent’s static method by using the parent:: notationn which will be covered later in next post.

Source : PHP5 Power Programming

Object Oriented Concepts In PHP5 (Part 1)

1 comments

1. objects
The main difference in OOP as opposed to functional programming is that the
data and code are bundled together into one entity, which is known as an object. Object-oriented applications are usually split up into a number of objects that interact with each other. Each object is usually an entity of the problem, which is self-contained and has a bunch of properties and methods.The properties are the object’s data, which basically means the variables that
belong to the object. The methods — if you are coming from a functional background — are basically the functions that the object supports. Going one step further, the functionality that is intended for other objects to be accessed and used during interaction is called an object’s interface.
Figure (A) represents a class. A class is a template for an object and describes what methods and properties an object of this type will have. In this example, the class represents a person. For each person in your application, you can make a separate instance of this class that represents the person’s information. For example, if two people in our application are called Joe and Judy, we would create two separate instances of this class and would call the setName() method of each with their names to initialize the variable holding the person’s name,$name. The methods and members that other interacting objects may use are a class’s contract. In this example, the person’s contracts to the outside world are the two set and get methods,setName()and get- Name().


class Person
Methods:
setName($name)
getName()

Properties:
$name
Fig.(A) Diagram of class Person.
The following PHP code defines the class, creates two instances of it, sets
the name of each instance appropriately, and prints the names:
class Person {
private $name;
function setName($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
};
$judy = new Person();
$judy->setName("Judy");
$joe = new Person();
$joe->setName("Joe");
print $judy->getName() . "\n";
print $joe->getName(). "\n";


2. DECLARING A CLASS
You might have noticed from the previous example that declaring a class (an object template) is simple. You use the class keyword, give the class a name,and list all the methods and properties an instance of this class should have:
class MyClass {
... // List of methods
...
... // List of properties
...
}
You may have noticed that, in front of the declaration of the $name property,we used the private keyword. We explain this keyword in detail later, but it basically means that only methods in this class can access $name .It forces anyone wanting to get/set this property to use the getName() and setName()methods, which represent the class’s interface for use by other objects or source code.


3. THE new KEYWORD AND CONSTRUCTORS
Instances of classes are created using the new keyword. In the previous example,
we created a new instance of the Person class using $judy = new Person();.
What happens during the new call is that a new object is allocated with its own copies of the properties defined in the class you requested, and then the constructor of the object is called in case one was defined. The constructor is a method named __construct(), which is automatically called by the new keyword after creating the object. It is usually used to automatically perform various initializations such as property initializations. Constructors can also accept arguments, in which case, when the new statement is written, you also need to send the constructor the function parameters in between the parentheses.
In PHP 4, instead of using __construct() as the constructor’s name, you had to define a method with the classes’ names, like C++. This still works with PHP 5, but you should use the new unified constructor naming convention for new applications.
We could have rewritten the previous example to pass the names of the people on the
new line:
class Person {
function __construct($name)
{
$this->name = $name;
}
function getName()
{
return $this->name;
}
private $name;
};
$judy = new Person("Judy") . "\n";
$joe = new Person("Joe") . "\n";
print $judy->getName();
print $joe->getName();
This code has the same result as the previous example.
NOTE : Because a constructor cannot return a value, the most common practice
for raising an error from within the constructor is by throwing an exception.
Source : PHP5 Power Programming

Website Security : Command Injection

0 comments
Another dangerous activity is executing shell commands whereby the user has supplied a part of the command. Mitigating this risk is very similar to mitigating the risk of SQL injection, although there are some specific PHP functions that you should learn. With properly filtered data, there are only two potential problems that you might
encounter regarding shell commands:

1. There might be metacharacters that can be used to execute arbitrary commands.

2. If the data being used to construct a command is intended to be a single argument, there might be characters within the data that cause it to be interpreted as multiple arguments instead.

These problems are solved with escapeshellcmd() and escapeshellarg(), respectively. Data passed through escapeshellcmd() will be escaped such that it no longer poses a risk of arbitrary shell command execution. Data passed through escapeshellarg() can safely be used as a single argument.


SOURCE:ZEND PHP5 CERTIFICATION STUDY GUIDE