[英]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. 其次 ,callclassA()方法正在创建和填充变量,但没有返回任何结果,也没有将结果保留在类变量中。 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? 第三 :您确定长方体的周长是正方形面积的9倍吗? 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. 您的代码太复杂,无法详细修改它,但这有望使想法成真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.