SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Zealot
    Join Date
    Sep 2010
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    parent::_construct()

    What does "parent::_construct()" do? Does it incorporate all the variables from "_construct" in class1?

    PHP Code:
    class class1 {
         var 
    $a;
         var 
    $b;
         function 
    _construct($a1,$b1){
              
    $this->$a1;
              
    $this->$b1;
         }
    }
    class 
    class2 extends class1 {
        function 
    _construct(){
            
    parent::_construct();
        }


  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Ok, quick OOP lesson

    Firstly your _construct should have 2 underscores before "construct" rather than one, so it should be: __construct.

    If class2 extends class1, it means that class2 takes on the variables and functions (in OOP, called: properties and methods). So in your post above, class 2 has $a and $b as variables. If you didn't create a __construct for class2, it would have taken on the __construct from class1.

    So if you override a method from class1 in class2, you can still access it from class1 using "parent::methodName();".

    Here's an example:
    PHP Code:
    <?php
    class Pet{
        protected 
    $Name '';
        protected 
    $Type '';
        public function 
    __Construct($Name$Type)
        {
            
    $this->Name $Name;
            
    $this->Type $Type;
        }
        public function 
    feed{
            return 
    "You have fed the {$this->Type} {$this->Name}";
        }
    }

    class 
    Dog extends Pet{
        public function 
    __Construct($Name){
            
    parent::__Construct($Name'Dog');
        }
        public function 
    wagTail(){
            return 
    "{$this->Name} is wagging their tail";
        }
    }

    $Brian = new Dog('Brian');
    echo 
    $Brian->feed();
    echo 
    '<br />';
    echo 
    $Brian->wagTail();
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


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
  •