Undefined variable in PHP

2

I'm trying to run this PHP code using object orientation and I'm having difficulty.

<?php 
class Circulo { 

    // declaração de propriedades 
    public $raio = 0;
    public $area = 0; 

    // declaração de método
    public function mostraArea(){ 
        echo $this->area;
    } 

    // declaração de método 
    public function calculaArea(){ 
        $this->area = 3.14*$raio*$raio;
    } 
} 

$circ1 = new Circulo;
$circ1->raio = 10;
$circ1->calculaArea();
$circ1->mostraArea();
?>

And in the browser the result is:

  

Notice: Undefined variable: radius in D: \ Web \ LocalUser \ PPI_11611208 slide45a.php on line 12

     

Notice: Undefined variable: radius in D: \ Web \ LocalUser \ PPI_11611208 \ slide45a.php on line 12 0

  • How is the radius variable not set? Being that I assigned a value to it on line 20.

It should probably be a basic POO concept question that I do not understand?

    
asked by anonymous 14.12.2017 / 19:36

2 answers

2

The variable $raio does not even exist. What is defined in your class is a property that has a different scope than a local variable. Your call always refers either to the object ( $this ) or the class / super class ( self / parent )

Change:

public function calculaArea() { 
    $this->area = 3.14 * $raio * $raio;
} 

To:

public function calculaArea() { 
    $this->area = 3.14 * $this->raio * $this->raio;
} 

So the calculation will be made on top of property and not on a variable (which does not exist).

Related:

Differences in the use of $ this, self, static and parent

When to use self vs $ this in PHP?

    
14.12.2017 / 19:44
0

The error is due to the $raio variable not found within the calculaArea method, to use an outside variable, use%

    
14.12.2017 / 19:44