Reading Note 4 – PHP 5 Advanced OOP and Design Patterns

OK. It’s Object Oriented Time!

1. Because a constructor cannot return a value, the most common practice for raising an error from within the constructor is by throwing an exception.

2. $obj = NULL will destruct the obj (or __desctruct() ill be called.

3. Static properties are defined by using static keywords, and you can think it as global variable that sit inside the class, but are accessible from anywhere via the class. Static property is used in a singleton pattern.

4. Static properties or methods can be called outside the class without creating an instance.

static staticproperty;

$this->staticproperty //THIS IS WRONG!!!!

5. parent:: and self::
They can access to static members, methods (both static and non-static method), and constants.

class A{
public $abc = 2;
function getabc(){
echo self::abc; //THIS IS WRONG, because abc is not static
Class B extends A{
function getabc(){
echo parent::abc; //HIS IS WRONG, because abc is not static

6. public protected, private are access modifiers for both properties and menthods

7.class constants do not use the define() function, which is used for global constant, but use the “const” keyword.

class myclass {
const RD = "red";

8. polymorphism uses “extends” keyword and means inheritance

9. PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method’s signature – they cannot define the implementation.

10. In PHP, you can only extends from one parent class, but you can use implements to archive multiple inheritance.

class A implements B, C, ... {

11. interface class like abstract. So no implantation of method and can not be directly instantiated. The different is that you can only extend from one abstract, but can extend from multiple interfaces.

12. final methods.
If you want to make sure that a method cannot be re-implemented in its derived classes, then use final access modifier.

13. final classes.
Final classes are not allowed inherited.

12. classes cannot be defined as abstract, final, but all classes are public in PHP. There’s no such thing as a “private/protect class”.

13. Exceptions
When using exceptions, follow these basic rules (both for performance and code-manageability reasons):

  1. 1. Remember that exceptions are exceptions. You should only use them to handle problems, which brings us to the next rule….
  2. 2. Never use exceptions for flow control. This makes the code hard to follow (similar to the goto statement found in some languages) and is slow.
  3. 3. The exception should only contain the error information and shouldn’t contain parameters (or additional information) that affect flow control and logic inside the catch handler.

14. Example to catch dived by zero exception
PHP5 brought exceptions to the table, and newer PHP provided libraries (PDO) will throw exceptions when bad/unexpected things happen. Hoever, the core codebase was NOT rewritten to use exception. Core functions and operations still rely on the old error system. If you want to “catch” these, you’ll need to set a custom error handler that will detect division by zero errors and do something about them.

   //$a = 1/0;
   $a = devide(1,0);
   echo $a;
catch(DevidedByZeroException $e1){
   echo $e1->getMessage();
   print " in file " . $e1->getFile();
   print " on line " . $e1->getLine() . "\n";
catch(Exception $e){
   echo $e->getMessage();

function devide($a, $b){
      throw new DevidedByZeroException("Division by zero is invalid");
      return $a/$b;

class DevidedByZeroException extends Exception {
   function __construct($message)

14. __autoload()

function __autoload($class_name) {
include $class_name . '.php';

$obj = new MyClass1();
$obj2 = new MyClass2();

spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future.

// function __autoload($class) {
// include 'classes/' . $class . '.class.php';
// }

function my_autoloader($class) {
include 'classes/' . $class . '.class.php';

//as php5.1.2
// you can have multiple callback functions

// Or, using an anonymous function as of PHP 5.3.0
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.class.php';

Reading Note 3 – PHP 5 Advanced OOP and Design Patterns

Basic but you may not know php syntax

1. use variable as variable name

$file1 = "hello";
$file2 = "world";
$file3 = "php";

for($i=1; $i<4; $i++){
   $filename = "file" . $i;
   echo $$filename . "\n";
   //or ${$filename};

2. if set a variable as NULL, then this variable will be noset (!isset)

$a = null;
   echo "you cannot see this";
   echo "set to null means no set";

3. Check if all variable have been defined using isset

   echo "yes, all set";

4. The Difference between empty and isset is that empty is to check if a variable is not set or is assigned a false value. isset is check if a variable is set.

5. What's superglobals? As a general rule, PHP does not support global variables. But there are some variables called superglobals, which are predefined by PHP and can be accessed from any scope. For example, $_GET, $_POST, $_COOKIE, $_SESSION, $_ENV, $_SERVER.

6. String Offerset - use to easy manipulate the any char in a string.

$str = '17';
$str{1} = '2'; //replace the second position of str to be '2', so the str is '12' now
$str[6] = 7; //php4 syntax, still valid in php5, but should use {} instead in php5
echo $str; //so now the str is '12    7'. after 2 there are 4 empty chars.

7. true or false of Array, Object, Resource.
a. If $arr is an empty array, $arr is false, otherwise, it's true
b. If $obj is an object, and $res is a resource, then $obj and $res are always true value

8.each() and reset()
The each function returns the current key/value pair and advances the internal pointer to the next element. Note that The each function returns an array with 4 pairs of items. For example:

$ages = array("John" => 28, "Barbara" => 67);
//reset($ages); //reset if needed
$person = each($ages);
    [1] => 28
    [value] => 28
    [0] => John
    [key] => John

list($name,$age) = each($ages);
echo $name . ": " . $age . "\n";
//You got: Barbara: 67. Because you did not use reset, and indexes 0 and 1 returned by each() are assigned to the list() construct.

$members = array("John", "Barbara");
$person = each($members);
    [1] => John
    [value] => John
    [0] => 0
    [key] => 0

9. The cast oprators
It changes the type of variable.

10. Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes:

LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

(int) $str is the same as (interger) $str
(bool) $str is the same as (boolean) $str

11. @ is the silence oprator, add @ before a function will silences error message.

12 eval() is similar to include, but instead of compiling and executing code that comes from a file, it accepts the code as a string. (Only do it when you can't do without) For example, in the solr,

$code = file_get_contents('http://localhost:8983/solr/select?q=iPod&wt=php');
//code is string, for exmaple,  'array("k1"=>"v1", "k2"=>"v2")...'
eval("\$result = " . $code . ";"); //this will assign array to $result

13. static variables.
Static variables only run at the first time (and only the first time), so it can be used in a function, where you only trigger something when function is called at the first time.

$count = 5; // "outer" count = 5

function get_count()
    static $count = 0; // "inner" count = 0 only the first run
    return $count++; // "inner" count + 1

echo $count; // "outer" count is still 5 
++$count; // "outer" count is now 6 (but you never echoed it)

echo get_count(); // "inner" count is now + 1 = 1 (0 before the echo)
echo get_count(); // "inner" count is now + 1 = 2 (1 before the echo)
echo get_count(); // "inner" count is now + 1 = 3 (2 before the echo)

Reading Note 2 – PHP 5 Advanced OOP and Design Patterns

Problem of Object Orient in PHP4.

  1. pass an object to a variable, a copy of the object would be created unless you pass it by reference (&)
  2. prevented implementing some additional features on top of the existing object model, such as public/private/protected, unified constructor/destructor name, interfaces, instanceof (instead of is_a() in PHP4), final methods/classes, __clones, class constants, static methods/members, abstract classes/methods, class type hints in function declarations, iterators, __autoload()

New features in PH5

  1. Error handling
  2. foreach with references and pass references into function
  3. all XML extensions have been rewritten to use the superb libxml2 XML toolkit
  4. New MySQLi (MySQL Improved) Extension
  5. SQLite extension
  6. Tidy Extension
  7. Perl Extension
  8. New Memory Manager
  9. drop support for windows 95

Reading Note 1 – PHP 5 Advanced OOP and Design Patterns

Main Different between PHP3 and PHP4

While PHP 3 still continuously parsed the scripts while executing them, PHP 4 came with a new paradigm of “compile first, execute later.” The compilation step does not compile PHP scripts into machine code; it instead compiles them into byte code, which is then executed by the Zend Engine, the new heart of PHP 4.

  1. PHP 4.1.0, introduced superglobals such as $_GET and $_POST. Superglobals can be accessed from within functions without having to use the global keyword. This feature was added in order to allow the register_globals INI option to be turned off.
  2. PHP 4.2.0 With the new superglobals in place, on April 22, 2002, it was released with the register_globals turned off by default.
  3. PHP 4.3.0, the last significant PHP 4 version, was released on December 27, 2002. This version introduced the Command Line Interface (CLI), a revamped file and network I/O layer (called streams), and a bundled GD library.

What’s register_golbals – why it’s bad

register_globals is a feature in PHP which automatically converts input variables like “?foo=bar” in to a PHP variable called $foo. Because many people do not check input variables properly, many applications had security holes, which made it quite easy to circumvent security and authentication code.

Main features of PHP5

  1. Rewrite the Object Oriented part
  2. new SimpleXML extension
  3. SOAP
  4. MySQLi

How to download file from Github

Github probably the most popular project hosting site in the world. A lot of open source projects are hosted on Github. You may like me often to download open source code from Github. If you are GUI user, then there is no problem to download the source code, but if you are command line user, then you may have a little trouble. Because the download link on Github is not obvious. You can can use wget to download it. Fortunately, there is another handy tool you can use, curl.

You can do the following, it works for both tarball and zipball.

curl -L > jquery-file-upload.tar
curl -L >

If the file is in tar format (tarball), you can even extract the tar file on fly by the following command,

curl -L | tar xz

The Very First Steps After a Fresh Firefox Install

Just got your new computer, not matter Mac or Windows, as a web developer, you may install Firefox first. so I’ll share with you my “first steps” after a fresh install to get Firefox set up to my liking. This involves some universally useful add-ons (specially for a web developer) and changing settings.

At the time of this writing, I just bought a new laptop (Latitude E6410) and installed Firefox (V3.6.10) definitely.

Add ons

Web Developer

Just like its name, Web Developer is mainly for Web Developer. But I think even for other users, it’s indeed a handy tool. For example, you can easily delete cookies set by current website (not remove other cookies that you may want to keep), and you can view a website’s images information. If you are web developer, then there are a lot of great thing this add-on provides, such as viewing Frame source code/Generated source code, resizing browser window to any size, using ruler to measure the size of page objects, etc.


Another great tool for every web developer for sure. The top feature of Firebug is that you can click on the page element to inspect and edit (both html and css in a real time) and it’s also a very good JavaScript debugger.


Check and copy color code of any spot on your browser. Colorzilla also includes color picker, color palettes and page zoomer.

Google Toolbar

There are tons of browser toolbars, Yahoo, MSN, Google, etc.  Almost everyone makes toolbar. I hate to install toolbar because it makes browse window crowding, but I do install Google Toolbar, because I use Google services a lot, which help me easily access Google service via various buttons.


I have been used XMarks for a few years, I like it very much. It helps me sync bookmarks anywhere on different computers. Unfortunately, recently they announced that XMarks will be shut down on January 10 2011. I am going to try Firefox Sync.

Firefox Settings

Rearrange Toolbars

The great feature I first see in Firefox is that it allows you to add or remove itms by dragging to or from the toolbars by right click on toolbar area and select customize. For example, Google toolbar has search box and Firefox itself has a search box, you can drop one off.

Open search result in a new tab

By default, search box returns search result in the current page, which is annoying sometimes. The quick tweak is press ctrl before you hit enter, but I always forget to do so. Fortunately, there is a persisted way to ‘fix’ this.

  1. Type ‘about:config’ in Address bar
  2. Type ‘search’ in Filter bar
  3. Find a Preference Named ‘’; double click it to set its Value to ‘true’

That’s it! You may also have your “first steps”, and you are welcome to add some here.

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging.

Yes, this is my first post (?p=1). I have used WordPress on many sites, and used to delete this post come with WordPress installation, but this time, I would like to do something different.

I have planed to create this site including registering this domain name ( for a while. But I am quite busy those days, so it’s kept being postponed.

Today, GoDaddy is offering Domain Name Registration for $0.99 for 1 year with code SCHOOL99 (note: Expires 8/31 or 7500 redemptions), seems to me a good deal. GoDaddy offers this kind of deal every few months, I missed it last time on 07/20. Not matter what I should catch it this time. Finally, I registered caiapps, which stands for Cai Applications, and Cai is my last name, and I am an web developer and hopefully I can show you some of my works (applications) here.

Second thing I would like to share with you is about my new hosting. I got tired with IXWebhosting (sucks), I was looking around for an affordable and reliable hosting for a while. And I found an month ago, seems to me a pretty good hosting. I really like the way they say in their host plans, that Disk Space(DS)/Bandwidth(BW) are limited.  In these days, you must see too many companies are promoting unlimited DS/BW. Do you believe it? I am not, in my opinion, for an shared hosting, you should not expect too much. When you just start your website, you don’t need unlimited DS/BW but stable and reliable hosting.  Another hosting I have been used is Inmotion, which is pretty good, but the price is a bit higher. Guess what? Hawk Host have a pretty good deal running now (50% off using the coupon august2010. Offer Valid | 11:57 am Aug 1 – 11:58 am Sep 1, 2010.) I only paid about $30 for an entire year for standard plan.

I just installed WordPress for this first post . More and more will be coming soon, stay tuned.