PHP Introduction to Classes

Discussion in 'Web Design & Programming' started by RHochstenbach, Mar 13, 2012.

  1. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    PHP 5 has introduced a new way of programming, called Object-Oriented Programming (OOP) which is also used in most system programming languages. OOP lets you work with reusable objects which makes your code cleaner and easier to read. This is especially useful with big projects.

    PHP uses a new element called a 'class'. A class can be compared with a function. If you don't know what functions are or how they are used in PHP, make sure to read this thread about functions first.

    Functions vs. Classes
    A function is a block of code which executes all instructions it contains in order and optionally returns a value. You can pass one or more parameters (values) with a function. You can't access any items like variables inside a function from the outside, and after executing it's destroyed until you call it again.

    A class on the other hand is not destroyed after executing. You basically load a new copy of a class each time you call it. When a class is loaded, you can access variables and execute functions inside it and repeat this for as many times as you want.

    For example, you can have a class that manages the properties of cars. I can load one copy of the class and give the car a blue color, and load a second copy and give that car a yellow color. Copy 1 is blue and copy is yellow. These copies will remain loaded unless you destroy them or load a different page.

    Construction of a Class
    In this example I will show you how a class looks like that manages cars. I will call it 'carManager'. Don't yet focus on the actual code, only look at how it's divided into segments:
    PHP:
    class carManager {
        
    // Defining properties here.
        
    public $brand;
        public 
    $model;
        public 
    $doors;
        public 
    $type;
     
        
    // Creating Methods
        
    public function setBrand($brand_value) {
              
    $this->brand $brand_value;
        }
     
        public function 
    setModel($model_value) {
              
    $this->model $model_value;
        }
     
        public function 
    setDoors($doors_value) {
              
    $this->doors $doors_value;
        }
     
        public function 
    setType($type_value) {
              
    $this->type $type_value;
        }
     
    }
    A class is divided in two sections as you can see in the above example. A part where properties are defined and a part where methods are placed. More about that in the following section.

    Properties and Methods
    Properties are the equivalent of Variables inside classes. They contain information about the class, in the above example they contain the information about a car. Hence the name 'properties'.

    Methods are the equivalent of Functions inside classes. They can perform an action inside the class and work just like regular functions (can take arguments and can return data). Notice that the arguments that are passed in the methods ($brand_value, $model_value etc.) do not have to be declared, as they are only being used inside the methods (which really work like 'regular' functions).

    Permissions
    Notice the 'public' keyword in front of each property and method? This means that these items can be called from outside the class. Other keywords are 'protected' and 'private'. Protected means that it can only be accessed from inside the class and child classes (more about that later). Private means that is can be only accessed from inside the class. A rule of thumb with classes is that you should only give the necessary permissions outside processes need to do their job. If a property or method should only be called from within a class, then don't give it the 'public' keyword, but use 'protected' or 'private' instead.

    Calling a class
    Now it's time to do the actual work. Put the carManager class at the top of the file.

    PHP:
    class carManager {
        
    // Defining properties here.
        
    public $brand;
        public 
    $model;
        public 
    $doors;
        public 
    $type;
     
        
    // Creating Methods
        
    public function setBrand($brand_value) {
              
    $this->brand $brand_value;
        }
     
        public function 
    setModel($model_value) {
              
    $this->model $model_value;
        }
     
        public function 
    setDoors($doors_value) {
              
    $this->doors $doors_value;
        }
     
        public function 
    setType($type_value) {
              
    $this->type $type_value;
        }
     
    }
    Now I'll create a new instance (copy) of the carManager class and I'll put it in the variable '$mycar'. It must be connected to a variable, because it must have some name to access it after creating it.

    PHP:
    // Creating a new instance of the carManager class
    $mycar = new carManager();
    We can now connect to the instance of the class using the '$mycar' variable. I will now execute the methods in the class to set the properties of the car.

    PHP:
    $mycar->setBrand("BMW");
    $mycar->setModel("M5");
    $mycar->setDoors("4");
    $mycar->setType("Sedan");
    As you can see, I have now executed the methods in the class. Notice that all those methods need to have the 'public' keyword. Otherwise there would be an error message, as there wouldn't be enough permissions. We can now access the properties.
    PHP:
    echo $mycar->brand;
    // echoes 'BMW'
     
    echo $mycar->model;
    // echoes 'M5'
     
    echo $mycar->doors;
    // echoes '4'
     
    echo $mycar->type;
    // echoes 'Sedan'
    Notice the arrow '->' after the variable and no dollar sign ( $ ) in front of the property name. We can even create another copy if we want.

    PHP:
     
    $mycar2 
    = new carManager();
    $mycar2->setBrand("Cadillac");
    $mycar2->setModel("Escalade");
    $mycar2->setDoors("4");
    $mycar2->setType("SUV");
     
    echo 
    $mycar->brand;
    // echoes 'BMW'
     
    echo $mycar2->brand;
    // echoes 'Cadillac'
    As you can see from the previous example you can have as many different instances of a class as you want. But keep in mind that this consumes resources. So if you don't need these instances anymore, destroy them with 'unset()':
    PHP:
    unset($mycar);
    unset(
    $mycar2);
    Construct and destruct
    In the previous example we had to call each method separately and also destroy each class instance manually. This can be done easier using the construct and destruct methods.

    A construct is a special method that will be executed as soon as you declare a new instance. To create a construct, create a public method called '__construct'.

    PHP:
    class carManager {
     
        public 
    $brand;
        public 
    $model;
        public 
    $doors;
        public 
    $type;
     
        public function 
    __construct() {
              echo 
    "New car loaded!";
        }
        public function 
    setBrand($brand_value) {
              
    $this->brand $brand_value;
        }
     
        public function 
    setModel($model_value) {
              
    $this->model $model_value;
        }
     
        public function 
    setDoors($doors_value) {
              
    $this->doors $doors_value;
        }
     
        public function 
    setType($type_value) {
              
    $this->type $type_value;
        }
     
    }
    Now we'll call a new instance of the class:
    PHP:
    $mycar = new carManager();
    // echoes 'New car loaded!'
    We can even pass the arguments for each of the methods to the construct method. So all 4 values only have to be passed at the time of declaration. The internal methods will only be used by the class, so we can change the permissions to 'protected':

    PHP:
    class carManager {
     
        public 
    $brand;
        public 
    $model;
        public 
    $doors;
        public 
    $type;
     
        public function 
    __construct($brand_input,$model_input,$doors_input,$type_input) {
              
    $this->setBrand($brand_input);
              
    $this-> setModel($model_input);
              
    $this-> setDoors($doors_input);
              
    $this-> setType($type_input);
        }
        protected function 
    setBrand($brand_value) {
              
    $this->brand $brand_value;
        }
     
        protected function 
    setModel($model_value) {
              
    $this->model $model_value;
        }
     
        protected function 
    setDoors($doors_value) {
              
    $this->doors $doors_value;
        }
     
        protected function 
    setType($type_value) {
              
    $this->type $type_value;
        }
     
    }
    Now we call the class like this:
    PHP:
    $mycar = new carManager("BMW","M5","4","Sedan");
    All arguments will be passed to the methods. You can now access each property as done earlier in this tutorial.

    If needed, we can destroy a class using the 'destruct' method. We can destroy a class automatically by adding it to the bottom of the class:
    PHP:
    public function __destruct() {};
    if you want to do this on command only, put it inside another method:
    PHP:
    public function destroyme() {
        public function 
    __destruct() {};
    }
    The $this keyword
    You might be wondering what the '$this' keyword does inside the class. Each property or method inside the class needs to be accessed this way. When designing the class, you can't know which variable name is going to be used to declare the class. Therefore '$this' stands for 'this class'. This is not needed for variables that are passed as arguments inside a method.
     
    peazz likes this.
  2. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    Child Classes
    A child class is a class that extents an existing class to add additional features. Let's say I want to create a newer class for the car that also lets me specify the color of the car. Instead of creating a new class, I'll extend it using the 'extends' keyword.


    PHP:
    class carManager {
        
    // Defining properties here.
        
    public $brand;
        public 
    $model;
        public 
    $doors;
        public 
    $type;
     
        
    // Creating Methods
        
    public function setBrand($brand_value) {
              
    $this->brand $brand_value;
        }
     
        public function 
    setModel($model_value) {
              
    $this->model $model_value;
        }
     
        public function 
    setDoors($doors_value) {
              
    $this->doors $doors_value;
        }
     
        public function 
    setType($type_value) {
              
    $this->type $type_value;
        }
     
    }
     
    class 
    betterCarManager extends carManager {
        public 
    $color;
     
        public function 
    setColor($color_value) {
              
    $this->model $color_value;
        }
     
     
    }

    Now declaring the new class. Notice that I am accessing the properties and methods of the old 'parent' class.


    PHP:
    $mycar = new betterCarManager();
     
    $mycar->setBrand("BMW");
    $mycar->setModel("M5");
    $mycar->setDoors("4");
    $mycar->setType("Sedan");
    $mycar->setColor("blue");
     
     
    echo 
    $mycar->brand;
    // echoes 'BMW'
     
    echo $mycar->model;
    // echoes 'M5'
     
    echo $mycar->doors;
    // echoes '4'
     
    echo $mycar->type;
    // echoes 'Sedan'
     
     
    echo $mycar->color;
    // echoes 'blue;

    Since I am now only accessing the properties and methods of the carManager class through its child class, I can change the permissions from 'public' to 'protected' in the carManager class. Can't change it to 'private' as this excludes the child class from accessing these items.

    We can also return and echo items from the carManager class using the 'parent::' keyword.

    PHP:
     
    class betterCarManager extends carManager {
        public 
    $color;
     
        public function 
    setColor($color_value) {
              
    $this->model $color_value;
        }
     
     
        public function 
    getBrand() {
              echo 
    "The brand is: ".parent::$brand;
        }
    }
     
    Keep in mind that a child class may not extend another child class. So the following would be illegal:
    PHP:
    class carManager {
        
    // code for the parent class
    }
     
    class 
    carColorManager extends carManager {
        
    // code for the child class
    }
     
    class 
    carWeightManager extends carColorManager {
        
    // code for the child class
    }
     
  3. RHochstenbach

    RHochstenbach Administrator Staff Member

    Likes Received:
    26
    Trophy Points:
    48
    Static Properties
    There are two types of properties, dynamic and static. The properties in the examples above are all Dynamic, because they can be changed. You can access them using '$this->property' or '$class_instance->property'. Static properties can not be changed, they get assigned a value when being declared. This is useful to have the user of your class change specific settings that affect the way the application runs.

    Declaring a static property works just the same as a dynamic property. The only difference is that you add the 'static' keyword. To access the property, you use 'self::$property' inside the class, and 'class_instance::$property' outside the class.

    PHP:
    class carManager {
     
        public static 
    $owner "John Doe";
        public 
    $color;
     
     
        public function 
    setColor($color_input) {
              
    $this->color $color_input;
        }
     
        public function 
    getInfo() {
              echo 
    "The color is ".$this->color.". The owner is ".self::$owner;
        }
    }
     
    // Create a new instance
    $mycar = new carManager();
     
    // Set the color
    $mycar->setColor("green");
     
    $mycar->getInfo();
    // The color is green, The owner is John Doe
     
    echo $mycar::$owner
    // John Doe
    The rules for Classes
    When working with classes, keep the following rules in mind:
    • All properties (except for method arguments) need to be declared before using.
    • Dynamic Properties and methods need to be accessed with $this->property or $this->method().
    • Static Properties need to be accessed with self::$property. They have the 'static' keyword and can not be changed after declaring.
    • Give each property and method only the permissions needed to get the job done.
    • Child classes may only extend parent classes, not other child classes
    • Destroy class instances you don't need anymore.
    That concludes the tutorial about classes. if you have any questions, don't hesitate to ask :)
     
  4. allisonsmith

    allisonsmith Geek

    Likes Received:
    1
    Trophy Points:
    8
    Wow that is a tremendous post,,thanks :)
     
  5. Archana Nair

    Archana Nair Geek Trainee

    Likes Received:
    1
    Trophy Points:
    1
    Great piece of information, being so useful.
     
  6. Mr Paul

    Mr Paul Geek Trainee

    Likes Received:
    0
    Trophy Points:
    1
    Thanks to share this valuable info.
     

Share This Page