Undefined variable in PHP

Asked

Viewed 1,276 times

2

I am trying to run this PHP code using object orientation and am having difficulties.

<?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 defined? Since I assigned a value to it on line 20.

Probably must be a basic question of POO concept that I didn’t understand?

2 answers

2


The variable $raio does not exist at all. What is defined in your class is a property that has a different scope than a local variable. Your call always refers 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 done over property and not 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?

0

The error is due to variable $raio not found within the method calculaArea, to use an out-of-method variable, use the $this->nome_da_variavel

Browser other questions tagged

You are not signed in. Login or sign up in order to post.