KingKongFrog
KingKongFrog

Reputation: 14419

How to "hide" private variable in PHP class

I might not have a good understanding of this, but since the "username" variable is private. Shouldn't this not be a part of the return? How do I make it so the $username is private and not outputed, but the public member is?

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"
}

Upvotes: 3

Views: 2121

Answers (3)

Curious Harsh
Curious Harsh

Reputation: 1

<?php class Demo {
private $string_var='yes';
protected $int_var=50000;
public $float_var=12.000;

public function __debugInfo() 
{
    return [
        'propString' => $this->string_var.'No',
    ];
} } var_dump(new Demo());    ?>

https://www.php.net/manual/en/language.oop5.magic.php#object.debuginfo

Upvotes: 0

Asif Iqbal
Asif Iqbal

Reputation: 1236

I have understood your concern. First of all, let me discuss about the variable scope private. private variable is private in the current class. If you use the class in another class private variable will not work. So, you have to use an another 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);

?>

Upvotes: 3

David Wyly
David Wyly

Reputation: 1701

Note: Don't ever use var_dump to render your class unless it's for debugging purposes.

Even though this is not the intent of private scope, interestingly enough, you can use echo json_encode($object); and the private variables within the class will not be outputted. You can then 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 up more on proper private/protected/public usage here

Upvotes: 2

Related Questions