0

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. I'm pretty new to php, and I'm studying online, so I'm probably doing something stupid. I'm also getting "call to undefined function" about the "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);
?>
0

1 Answer 1

1

There is a difference between $radius and $this->radius. The set_radius() method in your code sets some global variable, not as intended the object property. And there indeed is not method get_radius() defined anywhere...

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.

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:

$mySphere = new sphere(5);
echo $mySphere->get_area(5);
Sign up to request clarification or add additional context in comments.

1 Comment

@TanyaBranagan Sure it does :-) You are welcome, keep on learning and join us!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.