Steven Matthews
Steven Matthews

Reputation: 11275

Overwriting a function in a class in PHP

So I have a function in a PHP class, and I would like to have a modified version of that function for another class (an extended class).

Would I just recreate the class with my modifications inside the extended class? How would I go about having a function that acts differently in my extended class?

Upvotes: 0

Views: 129

Answers (1)

TiMESPLiNTER
TiMESPLiNTER

Reputation: 5889

You can override methods in child classes like this:

<?php

class A {
    public function printText($param) {
        echo 'foo';
    }
}

class B extends A {
    public function printText($param) {
        // Optional: This will call the printText method from the parent class A
        parent::printText($param); 

        echo 'bar';
    }
}

$instanceA = new A();
$instanceA->printText('sampleArg'); // Result: foo

$instanceB = new B();
$instanceB->printText('sampleArg'); // Result: foobar

/* EOF */

Important is, that the overridden method has the same amount of parameters as the parent class method else you get a PHP error.

Upvotes: 6

Related Questions