如何在PHP类中“隐藏”私有变量

时间:2015-05-11 20:40:39

标签: php class

我可能对此没有很好的理解,但由于“username”变量是私有的。这不应该是回报的一部分吗?如何使$ username成为私有而不是outputed,但是公共成员是?

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 个答案:

答案 0 :(得分:4)

我理解你的担忧。首先,让我讨论一下变量范围 private 。 私有变量在当前类中是私有的。如果您在另一个类中使用该类私有变量将无法工作。因此,您必须使用另一个类来保护您的私有变量。

<?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);

?>

答案 1 :(得分:1)

注意:除非出于调试目的,否则不要使用var_dump来渲染您的课程。

即使这不是私有作用域的意图,但有趣的是,您可以使用echo json_encode($object);并且不会输出类中的私有变量。然后,您可以在API中安全地使用此JSON。

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

答案 2 :(得分:0)

<?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