How to "hide" a private variable in a PHP class

I may not have had a good understanding of this, but since the "username" variable is private. Shouldn't this be part of the comeback? How do I make $ username private and not displayed, but a public member?

class MyClass 
{
    private $username = "api";


    public function create_issue()
    {
        $this->public = "Joe";
        return $this;
    }

}

$test = new MyClass();
$test->create_issue();

var_dump($test);

class MyClass#1 (2) {
  private $username =>
  string(3) "api"
  public $public =>
  string(3) "Joe"
}

      

+3


source to share


2 answers


I understand your concern. First of all, let me discuss the scope of the private variable . private variable is private in the current class. If you are using the class in another class, then the private variable will not work. Thus, you must use a different class to protect your private variable .



<?php

class MyClassProtected 
{
    private $username = "api";
    public function doSomething(){   
    // write code using private variable
   }

}


class MyClass
{   
    public function create_issue()

    {
       $test = new MyClassProtected();
       $test -> doSomething();
       return $this->public = "Joe";
    }
}


$test = new MyClass();
$test->create_issue();
var_dump($test);

?>

      

+4


source


Note. Never use var_dump

to render your class unless it's intended for debugging purposes.

Even though this is not the purpose of private scoping, interesting enough you can use echo json_encode($object);

, and private variables within a class will not be inferred. Then you can safely use this JSON in your API.



class MyClass 
{
    private $username = "api";


    public function create_issue()
    {
        $this->public = "Joe";
        return $this;
    }

}

$test = new MyClass();
$test->create_issue();

echo json_encode($test); // prints {"public":"Joe"}

      

Read more about proper private / secure / public use here

+1


source







All Articles