Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,038 questions

40,804 answers

573 users

How to run the parent class methods while overwriting in PHP

1 Answer

0 votes
class Test 
{
    public $pr = "Class property from class Test";
    
    public function __construct()
    {
        echo 'Constructor activated from class Test <br />';
    }
      
    public function __destruct()
    {
        echo '<br /> Destructor activated from class Test <br />';
    }
    
    public function setProperty($val)
    {
        $this->pr = $val;
    }
    
    public function getProperty()
    {
        return $this->pr;
    }
    public function f()
    {
        echo "Method f() from class " . __CLASS__ . "<br />";
    }
}
  
class MyNewClass extends Test
{
    // Declaring __construct() method again in MyNewClass to overwrite
    public function __construct()
    {
        parent::__construct(); // Call the parent class Test constructor
        echo 'Constructor activated from class MyNewClass <br />';
    }
    // Overwriting Inherited method f()
    public function f()
    {
        parent::f(); // Call the parent class Test f() method
        echo "Method f() from class " . __CLASS__ . "<br />";
    }  
}
 
   
$obj1 = new MyNewClass;

$obj1->f();


/*
run:

Constructor activated from class Test 
Constructor activated from class MyNewClass 
Method f() from class Test
Method f() from class MyNewClass

Destructor activated from class Test 

*/

 





answered Nov 3, 2015 by avibootz

Related questions

2 answers 735 views
2 answers 200 views
1 answer 115 views
...