简体   繁体   中英

call function from another class

im trying to call a function from another class called square function area to cuboid class.

abstract class Shapes
{
protected $name;
protected $colour;

function __construct($n, $c)
{
    $this->name   = $n;
    $this->colour = $c;
}

thankyou!

First : At least you should fix this method:

function callclassA()     {
    $area1=0;
    $classA = new Square();
    $area1 = $area1 + $classA->area();
}

This doesn't mean the whole will work, but at least you'll not be trying to call a method of a non object.

Second , the callclassA() method is creating and filling a variable, but it's returning nothing, and it's not persisting the result in a class variable. It would be better to try something like

class Cuboid extends Shapes
{
private $square=null;
private  $area=null;
function __construct($n, $c, $s, $ns)
    {
    parent::__construct($n, $c);   
    $this->square=new Square("Square",  $c, $s, $ns);
    $this->area = $this->square->area();
    }

    public function area()
    {
        return (6* $this->area);
    }
    public function perimeter()
    {
        return (9* $this->area);
    }   
}

Third : are you sure the perimeter of the cuboid is 9 times the square area? shouldn't be something times the square perimeter?

Independent classes shouldn't share data, it's not possible in any sane way. Instead, provide an adapter method to convert from a square to a cuboid:

class Square {

    protected $s;

    ...

    public function getSideLength() {
        return $this->s;
    }

}

class Cuboid {

    ...

    public static function fromSquare(Square $square) {
        return new static($square->getSideLength());
    }

}

$square = new Square(...);
$cube   = Cuboid::fromSquare($square);

Your code is too convoluted to adapt it in detail, but this gets the idea across hopefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM