-1

I have a class:

class A {
   protected $nome;       

   public function getNome() {
       return $this->nome . " exemplo";
   }

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

When i use the code:

$r = new A();
$r->setNome("My");
json_encode($r);

the code not returns because of the protected property, if the property is public the code returns but does'nt returns correctly.

1 Answers1

-1

As per the definition of class, we can access only public members outside class. So make $nome for public

class A {
    public $nome;  
    public function getNome() {
        return $this->nome . " exemplo";
    }

    public function setNome($nome) {
         $this->nome = $nome;
    }
}
$r = new A(); print_r($r);
$r->setNome("My");
echo json_encode($r);

OR

Return results to json_encode(if you don't make $Nome public), see the example:

$r = new A();
$r->setNome("My");
echo json_encode($r->getNome());
Surya prakash Patel
  • 1,512
  • 2
  • 24
  • 38