tags:

views:

77

answers:

4

How do I use a function that I defined in a parent class in the child class?

for example if i use a class like the below

<?php

class mat

{

function square($x)

{

return $x *$x;

}

}


class matchild extends mat

{

function doublesquare($x)
{

return square($x) * square($x)

}

}

?>

If I try the above , I get an error saying that the square function is not defined.

Answers and suggestions appreciated.

+10  A: 

You need to use this

return $this->square(x) * $this->square(x);

Check out PHP's basic documentation on classes and objects.

Pekka
thanks, i'll take a look at the manual
jimbo
A: 

In matchild's contructor call parent::__construct()

class matchild extends mat
{
    function __construct()
    {
        parent::__construct();
    }
}

Then you can call any method contained within the parent with $this->

Darrell Brogdon
You don't need to call a super class' constructor to use its methods.
James Socol
Right you are. Been doing it wrong all these years. :)
Darrell Brogdon
+3  A: 

Couple of issues with your snippet. But the answer you're looking for is:

$this->square()
Mike B
A: 

parent::square(x) * parent::square(x)

Jess