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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 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 860 views
2 answers 100 views
100 views asked Oct 11, 2024 by avibootz
2 answers 345 views
1 answer 220 views
...