PHP function of the class!

Asked

Viewed 35 times

2

I created a function within the class that takes a parameter and changes the value of a class variable, but it doesn’t work. Can anyone explain to me why? The result is NULL

<?php

class book{

    public $nome;

    function nao($x){
        $nome = $x;
    }
}

$pirata = new book();

$pirata->nao("caribe");

echo $pirata->nome;
var_dump($pirata);
  • 6

    You are not setting the field value $nome. The method nao is only creating a local variable (which cannot be accessed outside of it). To change a global field, use the $this, for example: $this->nome = $x

  • @Valdeirpsr It would be interesting if you put as answer and if possible exemplify, so that the question can be marked as answered.

  • yaaay gratiluz!!! worked perfectly =DDD

1 answer

1

The correct would be a Get and Set, and don’t forget the "$this" to reference a global value

<?php

class book{

    public $nome;

    function setNome($x){
        $this->nome = $x;
    }

    function getNome(){
        return $this->nome;
    }
}

$pirata = new book();
$pirata->setNome("caribe");

echo $pirata->getNome();

Browser other questions tagged

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