SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 40

Thread: Inheritance Class Question..

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Inheritance Class Question..

    Hi guys , Im fairly new to PHP OOP

    I am trying to work out when is inheritance necessary ?

    Example : I have 2 classes.

    PHP Code:
    <?php




    class company{
        
        public 
    $name;
        public 
    $address;
        public 
    $email;
        public 
    $phone;
        public 
    $web;
        

        
        public function 
    cleanup($name,$address,$email,$phone,$web){

            
    $this->name ucfirst(mysql_real_escape_string($name));
            
    $this->address ucfirst(mysql_real_escape_string($address));
            
    $this->email mysql_real_escape_string($email);
            
    $this->phone mysql_real_escape_string($phone);
            
    $this->web mysql_real_escape_string($web);
        }
        private function 
    checkemail(){
            
            
    $at stripos($this->email,"@");
            if (
    $at == 0){
                    
    $this->error.= "Invalid Email.";
                }else{
                    echo 
    "Valid Email.";
                }
            }
        
        private function 
    checkphone(){
            
            if(!
    is_numeric($this->phone)){
                
    $this->error.="Invalid Phone Number.";
                
            }
            
        }
            
            
    }
        
    ?>
    Now ofcourse a company will have employees so i thought this would be ok.

    PHP Code:
    <?php

    class employee extends company {
        

        public 
    $position;
        
        
        public function 
    setdetails($name,$address,$email,$phone,$web,$position){
        
            
        }
        
    }

    ?>
    Now my thinking behind this was that an employee would use all the same properties as a company but add one more being the employees position ?

    Is this correct ?

    If so can i add the details in company and then just append the employee position to the end of the setdetails in emplyee ?

    Or do both classes need to have the setdetails method?

    Im not sure how i go about doing this , So if its completely wrong please tell me why and where

    Kind Regards Shab

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,049
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    I would say the logic is a little off there.

    The general gist of inheritance is that if B extends A, then B is a subcategory of A.

    For example, you could have the class Vehicle. Car is a type of Vehicle, so Car could extend Vehicle. Ford is (in general terms) a type of car, so Ford could extend Car, and Fiesta is a type of Ford, so Fiesta could extend Ford.

    With your current logic, you're saying an employee is a type of company, which isn't the case.

    However, both have contact details, so you could do one of 3 things:
    1. Create a class Contact, which has contact details. Both Company and Employee extend Contact.
    2. Create a class Contact, which has contact details. Both Company and Employee have a variable Contact, which holds a Contact Object.
    3. Create an interface Contactable, and have methods such as getName(), getEmail() etc. Both Company and Employee implement this interface and have those methods


    Personally I'd prefer the third.

    You can then have functions such as:
    PHP Code:
    SendEmail(Contactable $Contact$Subject$Message){ 
    You could pass both Company and Employee as the first parameter, as both implement Contactable.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  3. #3
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can you explain in laymens terms when class inheritance is necessary

    Im really trying to get to grips with Classes and how they work.

    Im not sure how i would go about setting an extended class propertys which have been inherited from its parent.

    and would i need to call all the propertys held within the parent class in the extended class?

    So from the previous post it would seem you have the main object.

    Example :
    My object is a Camera.
    ( All cameras have the same methods, Take Picture)
    My Camera extension is Camera_Manufacturer
    ( A range of companys can make cameras)
    My other extension which extends camera is camera is MegaPixels.

    Is this the correct logic ?

    I think i could probably add MegaPixels to the Camera_manufacturer class but for the sake of this example im trying to take an object and blow it apart into as many extended classes as possible to understand classes a bit better


    Another Example :
    My Object is a User
    (Propertys : Username,Password)
    My Admin extends User
    (Because Admin also has a username and password but more methods than a normal user)
    My Super Admin extends User
    (Because Super Admin also has a username and password but has more methods than a User and Normal Admin.)


    Sorry for the bloated examples just want to clarify that im thinking along the right lines for PHP OOP now ?

    Many Thanks Shab.

    PS I have the propertys declared as public in my script above because i want to be able to insert a new company into the database from a html form. Can i still send POST vars if they are declared Private or Protected and Set the values from submitted form ?

  4. #4
    PHP Guru lampcms.com's Avatar
    Join Date
    Jan 2009
    Posts
    914
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The thing about OOP is that there are always more than one way to accomplish the same task.

    Your requirements are very simple right now, so it is OK to implement it the way you proposed. My advice to you would be to follow good practice in OOP and declare your vars as protected (not public), also try not to declare methods private, better use protected. This is just a general rule that if you follow it, there will be less pain for you later on when it comes to testing and debugging.

    Also don't worry too much that there may be other ways 'to do this', because there are always are other way. Just make it work, you can refactor later if you decide that something needs to be changed.

    I also noticed that you have this in your method:
    $this->error .=

    but you have not declared the $error = ''; in the beginning of class. This will cause an error. Also the object usually will work fine if you have not declared a property at the beginnig and then somewhere in your method are setting a property like $this->newprop

    But this will cause a huge headache if you ever decide to use a magic method __call() or __get()

    So better make sure you declare all the instance variables you can possible have in any of your methods.
    My project: Open source Q&A
    (similar to StackOverflow)
    powered by php+MongoDB
    Source on github, collaborators welcome!

  5. #5
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,049
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    The first part:
    My object is a Camera.
    ( All cameras have the same methods, Take Picture)
    My Camera extension is Camera_Manufacturer
    ( A range of companys can make cameras)
    My other extension which extends camera is camera is MegaPixels.
    Is incorrect.

    Extending something is basically narrowing it down. For example:
    An item has a certain weight, certain colours.
    A musical instrument is an ITEM (has weight and colours) but also has a sound
    A piano is a MUSICAL INSTRUMENT (which is, itself, an item), because it has a weight, colours, a sound - it also has other properties.
    A violin is also a MUSICAL INSTRUMENT, because it has the above. It's different to a piano, but it still falls under the category of a musical instrument.

    Back to your example:
    My object is a Camera.
    ( All cameras have the same methods, Take Picture)
    My Camera extension is Camera_Manufacturer
    ( A range of companys can make cameras)
    My other extension which extends camera is camera is MegaPixels.
    Is a camera manufacturer a camera? Is MegaPixels a camera? No, these are just properties of camera.

    As for your second part:
    My Object is a User
    (Propertys : Username,Password)
    My Admin extends User
    (Because Admin also has a username and password but more methods than a normal user)
    My Super Admin extends User
    (Because Super Admin also has a username and password but has more methods than a User and Normal Admin.)
    That's correct. An admin is a type of user, so it can be extended from user. Your super admin, however, is a type of Admin, so I'd extend Admin rather than User.

    PHP Code:
    Class User{
        protected 
    $Username$Password;
    }
    Class 
    Admin extends User{
        const 
    CAN_ADD 1CAN_EDIT 2CAN_DELETE 4;
        protected 
    $Privileges self::CAN_ADD//by default, can only add
    }
    Class 
    SuperAdmin extends Admin{
        function 
    __Construct(){
            
    $this->Privileges self::CAN_ADD self::CAN_EDIT self::CAN_DELETE;
        }

    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  6. #6
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    The first part:

    Is incorrect.

    Extending something is basically narrowing it down. For example:
    An item has a certain weight, certain colours.
    A musical instrument is an ITEM (has weight and colours) but also has a sound
    A piano is a MUSICAL INSTRUMENT (which is, itself, an item), because it has a weight, colours, a sound - it also has other properties.
    A violin is also a MUSICAL INSTRUMENT, because it has the above. It's different to a piano, but it still falls under the category of a musical instrument.

    Back to your example:

    Is a camera manufacturer a camera? Is MegaPixels a camera? No, these are just properties of camera.
    So looking at your example i could extend item ( which has weight , colours propertys ) with say Class TV ( With properys of Screen Size,Maker,Screen Type,HDReady) Is that correct?

    If this is correct i will try to write a couple of dummy classes with these various things and post them here for your scrutiny

    Bearing your Item,Musical Instrument classes Would you be able to post a small demonstration of what these would look like.

    I really appreciate your help here.

    Many Thanks Shab

  7. #7
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,049
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    Class Item{
        protected 
    $Colour$Weight;
    }
    Class 
    MusicalInstrument extends Item{
        protected 
    $Sound;
    }
    Class 
    Piano extends MusicalInstrument{
        protected 
    $Type$PedalCount;
    }
    Class 
    GrandPiano extends Piano{
        protected 
    $Manufacturer;
        function 
    __Construct(){
            
    $this->Type 'Grand';
            
    $this->PedalCount 3;
        }
    }
    Class 
    SteinwayGrandPiano extends GrandPiano{
        function 
    __Construct(){
            
    parent::__Construct();
            
    $this->Manufacturer 'Steinway';
        }

    Basically, there are practically infinite levels you could extend to, but you only really need a few. The main difference comes when theres something one object can do that others can't - for example, let's say a Steinway Grand Piano can fly, whereas others can't. Then you'd be able to do:
    PHP Code:
    Class SteinwayGrandPiano extends GrandPiano{
        function 
    __Construct(){
            
    parent::__Construct();
            
    $this->Manufacturer 'Steinway';
        }
        function 
    Fly(){
            
    //....
        
    }

    And you now have reasoning for extending that far.
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  8. #8
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ahh i think i understand now

    The included class would be a blueprint of said object and then the extended ones are merely variations of that object ?

    I wrote a small version of the item>instrument>tv i spoke about to see if i was understanding properly.

    PHP Code:
    <?php 
    $myitem 
    = new item;
    $myitem->set("Black","100");
    $newitem = new item;
    $newitem ->set("Red","85");

    $newitem->musical_instrument->set("BANG","DRUM");
    $myitem->TV->set("18","SONY");
    class 
    item{
        
        
        
        public 
    $colour;
        public 
    $weight;
        
        
        public function 
    set($colour,$weight){
        
         
    $this->colour $colour;
         
    $this->weight $weight;
        }
    }
    ?>

    <?php

    class musical_instrument extends item{
        
        public 
    $sound;
        public 
    $instrument_type;
        
        public function 
    set($sound,$type){
            
            
    $this->sound $sound;
            
    $this->instrument_type $type;
        }
        
        
        
    }
    ?>
    <?php


        
    class TV extends item{
            
            
        public 
    $screen_size;
        public 
    $maker;
        
        public function 
    set($size,$make){
            
            
    $this->screen_size $size;
            
    $this->maker $make;
            
        }
                    
    }


    ?>

    <?php 


    echo "
    Tv weight : "
    .$myitem->weight."kg,s<br/>
    Tv Screen Size : "
    .$myitem->screen_size." inches<br/>
    Tv Colour : "
    .$myitem->colour."<br/>
    Tv maker : "
    .$myitem->maker;
    // Hopefully would echo out "tv weight : 100kg,s , tv screen size : 18, tv colour: black, tv maker : SONY

    Gonna test this script now
    Thanks Shab

  9. #9
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,049
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ah, I see where you're being confused now.

    Object B extending object A doesn't change object A in any way. If 'Car' extends 'Vehicle', it doesn't make 'Car' a property of 'Vehicle'.

    It just means that 'Car' has the same properties/methods as 'Vehicle'. It's a bit like having a class and pasting the contents of 'Vehicle' into 'Car', but you get benefits such as polymorphism.

    Polymorphism is where an object (say Car) can be passed to a function which expects a Vehicle, and the methods/properties present in Vehicle can be used by that function because all classes extending Vehicle have those properties. Added methods/properties cannot be used (not sure if it's strict on that in PHP, but languages such as Java, C++ etc all demand that by expecting Vehicle, you can't use methods that are only in Car)
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  10. #10
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried the above code and it says this

    Notice: Undefined property: item::$TV in C:\wamp\www\testclass.php on line 4

    Fatal error: Call to a member function set() on a non-object in C:\wamp\www\testclass.php on line 4

    I think its basically saying to me that it cant find an object instantiated from the TV class but im not sure.

    Can you explain how i would access the TV class please.

    Many Thanks for all your replys and taking the time to reply to someone as lost as me lol

    Regards Shab

    PS did the above class inheritance look ok though or is that still wrong and i need to go back to the drawing board lol.

  11. #11
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @arkinstall

    Class SuperAdmin extends Admin{

    function __Construct(){

    $this->Privileges = self::CAN_ADD | self::CAN_EDIT | self::CAN_DELETE;

    }

    }

    Few years in PHP and tone of books and code passed through my hands and never saw this kind of 'bunch of properties assignment'. Explain please.

    @Shabalaka
    I think you can gain a lot from this article:
    PHP 101 (part 7): The Bear Necessities
    You can fine it at devzone subdomen on Zend's site.

    Cheers

    PS Cannot post links, have no enough posts ))

  12. #12
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,049
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Dusan G View Post
    Few years in PHP and tone of books and code passed through my hands and never saw this kind of 'bunch of properties assignment'. Explain please.
    You have, you just probably haven't realised it yet It's used more in other programming languages, but it is used in PHP too.

    When you're setting the error reporting in PHP, you're doing just this. For example, say you want no errors:
    PHP Code:
    error_reporting(E_ERROR E_WARNING E_PARSE); 
    This sets the error reporting to show errors, warnings and parse problems.
    PHP Code:
    error_reporting(0); 
    Set it to nothing
    PHP Code:
    error_reporting(E_ALL E_NOTICE); 
    This sets it to all errors apart from notices.

    This is simply bitwise operation. It's a bit like many booleans represented by one byte.

    Say a setting to allow adding of articles has the value 1, and the setting to modify them is 2. In terms of bits (binary), adding is 0001 and modifying is 0010.

    You can think of the final bit as 'the adding bit' and the one left of it as 'the modifying bit'.

    If a user has a permission level of 1 (0001), they can add articles only. If they have a permission level of 2 (0010), they can only modify articles. If they have a permission level of 3 (0011), they can do both.

    http://uk.php.net/manual/en/language...rs.bitwise.php
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  13. #13
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the advice , I will pop onto Zend website now and look at that PHP 101 , ( Only problem i tend to find is that they tend to use all the technical terms which for people such as myself can only confuse us more.)

    I just hope its all in laymens terms starting out with classes seems really quite hard. But im sure i will get there eventually lol

    Just a quick question regarding classes ( Cant remember where i watched a tutorial for classes in PHP ) But i can remember they said setting propertys like

    $myobject->myproperty = myvalue;

    Is bad practice i dont know if this is true.Can someone confirm this please or reiterate for me.

    Many Thanks Shab.

  14. #14
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Tutorials called 101 are for beginners in English learning system so to say.
    You forgot to instantiate musicalinstrument object and before doing that you cannot call its properties or methods.

  15. #15
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    actually you called it as if it is object's object.

  16. #16
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So i would need to instantiate 2 items and 1 TV item and 1 musical instrument ?
    $myitem = new item;
    $myTv = new TV;
    $myitem->$myTv->set("18","SONY");

    Like that ?

    then echo $myTv->screen_size would output Tv Screen Size : 18 inches?

    Many thanks for the replys.

    Regards SHab

  17. #17
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    so you should change it to

    $music_instrument_item = new musical_instrument;
    $music_instrument_item->set("BANG","DRUM");

  18. #18
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    __construct ( means the default for all new objects ) ?
    I will post my progress and my rendition as i think about it. Just to make sure that my thought process is correct.

    Regards Shab

  19. #19
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Read the article I've mentioned few post earlier... it is awesome for beginners.
    A lot will be answer to you instantly.
    'goto' now

  20. #20
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  21. #21
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Can i ask for a simple terms explanation regarding this line from PHP 101 please.

    class PolarBear extends Bear {

    // constructor
    public function __construct() {
    parent::__construct();
    $this->colour = "white";
    $this->weight = 600;
    }

    I understood all of it apart from this line parent::__construct();. I tried to understand the explanation of it but it just goes on about initialization of parent object etc

    Quote from PHP 101

    Note how the parent class constructor has been called in the PolarBear() child class constructor - it's a good idea to do this so that all necessary initialization of the parent class is carried out when a child class is instantiated. Child-specific initialization can then be done in the child class constructor. Only if a child class does not have a constructor, is the parent class constructor automatically called.

    Sounds all confusing to me....

    Regards Shab

  22. #22
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    now I can paste links

  23. #23
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    cool

    Just finished the Bear PHP 101 , Am gonna try to write an animal class which is similar to the Bear one from the Zend tutorial

    and then see if i can work out exactly how the code is working.

    I have written my own class to work with an addon from FlashLoaded.com,s photoflow flash addon. but because its only a single class it didnt use inheritance at all but maybe once i work out inheritance i can modify it to be a full class to utilise all the components from flashloaded

    Many Thanks for the link its really helpful.

    Regards Shab

  24. #24
    SitePoint Member
    Join Date
    Jan 2009
    Location
    Novi Sad, Serbia
    Posts
    15
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    it's not...

    what it says is that:
    if class you are making instance of has no __construct() method
    ONLY THAN
    parent __construct() will be called automatically (you don't need to embed call to it in child class)
    OTHERWISE
    if you have __construct() method in child class you are instantiating
    THAN
    you have to embed call to parent __construct() inside of __construct() of the child.

    c?

  25. #25
    SitePoint Enthusiast
    Join Date
    Aug 2009
    Posts
    45
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks
    I understand now

    Shab

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •