开发者

Php inheritance question

开发者 https://www.devze.com 2022-12-15 08:44 出处:网络
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

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 functio开发者_运维知识库n is not defined.

Answers and suggestions appreciated.


You need to use this

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

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


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

$this->square()


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消