0

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.

4 Answers 4

10

You need to use this

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

$this->square()

Comments

0

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

Comments

-2

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->

1 Comment

You don't need to call a super class' constructor to use its methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.