[英]How do I fix error “undefined variable” in php, when I have defined it?
I realise this is similar to many other questions, but I've read all of the, and I still can't solve my problem. 我意识到这与许多其他问题相似,但是我已经阅读了所有这些问题,但仍然无法解决我的问题。 I'm trying to define a class of Sphere, which can calculate various aspects of a sphere given its radius.
我正在尝试定义一个球体类,它可以根据球体的半径计算球体的各个方面。 However, I'm getting an error of undefined variable when I try to echo $radius (as a test) at the end of the script.
但是,当我尝试在脚本结尾处回显$ radius(作为测试)时,出现了未定义变量的错误。 I'm pretty new to php, and I'm studying online, so I'm probably doing something stupid.
我是php的新手,并且正在在线学习,所以我可能在做一些愚蠢的事情。 I'm also getting "call to undefined function" about the "echo get_area(5);"
我还收到有关“ echo get_area(5);”的“对未定义函数的调用”。 bit.
一点。
<?php
define("PI", 3.14);
define("fourOverThree", 1.25);
class sphere
{
private $radius;
//a method
public function set_radius($input)
{
$radius = $input;
}
public function get_diameter($radius)
{
$diameter = $radius * 2;
}
public function get_area($radius)
{
$area = PI * ($radius * $radius);
}
public function get_volume($radius)
{
$volume = fourOverThree * PI * ($radius * $radius * $radius);
}
public function __construct()
{
//stub
}
}
$sphere1 = new sphere;
$sphere1->set_radius(5);
echo $radius;
echo get_area(5);
?>
There is a difference between $radius
and $this->radius
. $radius
和$this->radius
之间有区别。 The set_radius()
method in your code sets some global variable, not as intended the object property. 您代码中的
set_radius()
方法设置了一些全局变量,而不是预期的object属性。 And there indeed is not method get_radius()
defined anywhere... 确实没有在任何地方定义方法
get_radius()
...
I guess this is something into the direction you are looking for: 我想这是您要寻找的方向:
<?php
class sphere
{
const PI = M_PI; // M_PI is one of php's predefined constants
private $radius;
public function set_radius($radius)
{
$this->radius = $radius;
}
public function get_diameter()
{
return $this->radius * 2;
}
public function get_area()
{
return self::PI * pow($this->radius, 2);
}
public function get_volume()
{
return (4/3) * self::PI * pow($this->radius, 3);
}
public function get_radius()
{
return $this->radius;
}
public function __construct($radius)
{
$this->radius = $radius;
}
}
$sphere1 = new sphere;
$sphere1->set_radius(5);
echo $sphere1->get_area(5);
A note about precisions: since this uses floating point arithmetic the results are not precise. 关于精度的说明:由于此方法使用浮点算法,因此结果不精确。 This is not a php specific issue, but one of how floating point arithmetic works.
这不是特定于php的问题,而是浮点算法的工作方式之一。
Instead of that setter set_radius()
I would also suggest to use the constructor for that instead, since a sphere without a diameter does not make any sense... So: 除了那个setter
set_radius()
我还建议使用构造函数代替它,因为没有直径的球体没有任何意义...所以:
$mySphere = new sphere(5);
echo $mySphere->get_area(5);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.