Object Oriented PHP-GTK2 - OOP Basics Chapter 2 Object Oriented PHP-GTK2 - OOP Basics Chapter 2
it's me, bob. lol. Object Oriented PHP-GTK2 OOPS

OOP Basics Chapter 2

The basics PHP5 object orientation, essential to successful PHP-GTK

Topic: PHP5 Object Orientation (View All Tutorials)
Keywords: php oop class object property method static extends constructor
Updated: 280 Days Ago, 2007/11/14 20:45

In This Document
Constructors
Extending Classes
Static Properties/Methods
Wrapping Up

Making Object Orientation Work For You

There are three more features of PHP5 OOP that are important to making it truely useful for programming. Without them, OOP could be looked upon as extra lines of code. With them, a uniform system of application development.

 

Construction and Auto-Defaults

One of the most useful features of classes is the ability to set default values on object creation. This is done by defining a method called __construct() in your class. This method works like other self-defined method except that when a new object is created with the new keyword it is automatically run. On the flip-side to that, the __destruct() method is run when the object is destroyed. For most general purposes it is not nessessary to define your own __destruct().

<?php
class OpticalDisc {
    const 
MAX_DATA '650MB';
    
    private 
$title;
    
    public function 
__construct() {
        
$this->title 'Standard CDROM';
        return;
    }
    
    public function 
set_title($text) {
        
$this->title $text;
        return;
    }
    
    public function 
get_title() {
        return 
$this->title;    
    }
}
?>

If you have ever burned a CD you have probably noticed that you can set the name of the disc, and you can only do it when you burn it. This is why the $title property is private, and I have created get and set methods for the title.

This class also introduces a new item, the class constant defined with the keyword const. These set keywords just like the define() function, once set they cannot be changed. You can check the maximum amount of data an optical disc can have on it by reading that constant like so:

<?php
echo("Max Data for Optical Disc: " OpticalDisc::MAX_DATA);
?>

Max Data for Optical Disc: 650MB

If you needed to access this class constant from inside the class, instead of referring to it as OpticalDisc::MAX_DATA you could read it as self::MAX_DATA - this way you could rename the class without having to edit the code inside. Class constants do not become passed to the objects, you always reference them statically. There is no need for them to be passed to the physical object because the constants job is to describe all objects of a type.

So how about using this Optical Disc class?

<?php
$disc 
= new OpticalDisc;
print_r($disc);
?>

//. bob@elenothar [/]$ php ~/disc.php
OpticalDisc Object
(
    [title:private] => Standard CDROM
)

 

Building Classes Off Classes

The other great feature of object orientation is the ability to create a new class based off one that already exists. This prevents you from having to recreate the entire class. Before we extend our Optical Disc class though, we need to make one small change to it.

Note

When you extend a class you are not modifing the original, you are creating a new class which is built off the original.

<?php
class OpticalDisc {
    const 
MAX_DATA '650MB';
    
    protected 
$title;
    
    public function 
__construct() {
        
$this->title 'Standard CDROM';
        return;
    }
    
    public function 
set_title($text) {
        
$this->title $text;
        return;
    }
    
    public function 
get_title() {
        return 
$this->title;    
    }
}
?>

Notice the private property $title is now a protected property. I have done this because we want our new classes built off this one to be able to modify their inherited title property. Note protected properties allow new classes built off that class to use the property, but we still cannot use it from outside the classes, same as private.

A Blank CD-R.

<?php
class CDR extends OpticalDisc {
    public function 
__construct() {
        
parent::__construct();
        
$this->title 'Blank CD-R';
        return;
    }
}
?>

Notice this class also has a __construct() method, and it is built off the original Optical Disc class. Because we want CD-R's to inherit all of the attributes of an Optical Disc, the first line in the CD-R __construct() calls the parent constructor.

The Parent? OpticalDisc is the Parent class. CDR is the Child class. The child inherits the Parent attributes and default values by executing the parent's constructor. The child then sets it's own default disc title.

<?php
$cdr 
= new CDR;
print_r($cdr);
printf("Max Data for a CD-R: %s\n"CDR::MAX_DATA);
?>

//. bob@elenothar [/]$ php ~/disc.php
CDR Object
(
    [title:protected] => Blank CD-R
)

Max Data for a CD-R: 650MB

When you extend a class, you also have the option to overwrite existing methods and class constants with new ones that pertain only to the child class (as well as any children classes built off that child class, thus it becomes a parent to the children as well)

A Blank DVD-R.

<?php
class SingleLayerDVDR extends OpticalDisc {
    const 
MAX_DATA '4.7GB';

    private 
$type;
    
    public function 
__construct() {
        
parent::__construct();
        
        
$this->type '-';
        
$this->title "Blank DVD{$this->type}R";
        return;
    }
    
    public function 
set_type($sign) {
        
$this->type $sign;
        if(
preg_match('/^Blank DVD[-+]R$/',$this->title)) {
            
$this->title "Blank DVD{$this->type}R";
        }
        return;
    }
    
    public function 
get_type() {
        return 
$this->type;
    }
}
?>

Here we defined a new private property, $type, because Recordable DVD discs can be of a type plus or minus. When we set the type, it checks if the disc is still blank and updates the title with the proper type character.

This class also overwrote OpticalDisc's MAX_DATA with it's own, since DVD's are quite a bit larger than normal CDs.

<?php
$dvdr 
= new SingleLayerDVDR;
$dvdr->set_type('+');
print_r($dvdr);
printf(
    
"Max Data for a Single Layer DVD: %s\n",
    
SingleLayerDVDR::MAX_DATA
);
?>

//. bob@elenothar [/]$ php ~/disc.php
SingleLayerDVDR Object
(
    [type:private] => +
    [title:protected] => Blank DVD+R
)

Max Data for a Single Layer DVD: 4.7GB

Overview Of Extended Classes

Here is an English translation of all the code above for our three classes, OpticalDisc, CDR, and SingleLayerDVDR.

  • OpticalDisc - A Standard CDROM. Can hold a max of 650MB of data.
  • CDR - An OpticalDisc that is recordable. Like an OpticalDisc it can hold a max of 650MB of data.
  • SingleLayerDVDR - An OpticalDisc that is recordable, but it can hold up to 4.7GB of data. It also can be of two types, DVD+R or DVD-R.

A slightly more technical overview of the same three classes. This layout shows the parent-child relationship between the classes.

  • OpticalDisc
    Max Data: 650 MB
    Default Title: Standard CDROM
    • CDR
      Max Data: 650MB
      Default Title: Blank CD-R
    • SingleLayerDVDR
      Max Data: 4.7GB
      Default Type: - (DVD-R)
      Default Title: Blank DVD-R

Some Common Questions asked, and some answers.

Can we change the title on all three classes?

Yes, each of these classes gain the set_title() method from the OpticalDisc class.

Can we change the -/+ type of a CDR?

No. Only SingleLayerDVDR has the set_type() method. This class was extended from OpticalDisc, and the method is unique to only SingleLayerDVDR objects and any classes which may be extended from SingleLayerDVDR in the future.

Why is this? Because real CD-Rs do not even have that option. Only recordable DVDs do.

Do my new classes aquire the Class Constants too?

Yes. Each of these classes have the MAX_DATA constant. They aquired it because they were extended from the OpticalDisc class which first defined it. Because of this you now have access to OpticalDisc::MAX_SIZE, CDR::MAX_SIZE, and SingleLayerDVDR::MAX_SIZE. Remember that the SingleLayerDVDR overwrote it's own copy of MAX_SIZE, thus reflecting the larger capacity of the disc.

Can I update the constants?

There is a reason they are called constant. The only way to change it would be to extend the class and overwrite it. From outside the class you cannot alter a class constant, you can only read them.

 

Static Properties and Methods

Refer back to the first instance of a class constant in this document. We had referenced it as "OpticalDisc::MAX_DATA". A breakdown of the physical syntax gives us "class::constant". This is known as referring to something that is a static member of the class. A member that is static can be accessed anywhere on the global scope where the class itself could be referenced, and it can be used independently of an object instance. In fact, an object never even has to be created to use static members, you could therefore use a class as a sort of Namespace for your data.

Constants are always static, however both properties and methods can also be made static. Take this example class:

<?php
class exampleClass {
    static 
$var1;
    
    static function 
myFunc() {
        echo(
"this is my static function.\n");
    }
}

exampleClass::$var1 'orange';
exampleClass::myFunc();
?>

No matter where or when we read exampleClass::$var1 again, it will return 'orange'. And the static method, it will output the same thing every time.

One note about static methods: unlike normal methods you do not get access to the $this object from within the method. This is because you have called the function statically which means without reference to an object.

Also remember when working on the code inside of a class, you should reference static members of that class with the self:: prefix instead of the class name.

 

Wrapping Up

Remember the rules about destroying objects. As your code becomes larger your system will have to devote more resources to it. This is true for any program. Free your objects when there is no use for them anymore.

<?php
unset($disc$cdr$dvdr);
?>

Was this document helpful? I appreciate your feedback.
What are the rules about reusing this code?


i can has web two point ooh // copyright © 2007-2008 bob majdak jr
[ xhtml css | firefox ie7 opera ]