【问题标题】:How to access Private properties in php or even can i?如何访问 php 中的私有属性,甚至可以访问?
【发布时间】:2014-08-17 08:29:05
【问题描述】:

我有一个简单的代码示例,我想在其中设置私有属性 $ttlBal。

<$php
$balance = new Customer;
$greeting = fopen("greeting.txt", "r");
while(!feof($greeting)){
    echo fgets($greeting) . "<br>";
}
fclose($greeting);
$balance->acctBal = 12;
$balance->deposits = 12;
$balance->fdr = 12;


$balance->findAvail($balance->acctBal, $balance->deposits, $balance->ttlBal);
class Customer{
    public $acctBal; 
    public $deposits;
    private $acctAvail;
    private $ttlBal;
    public $fdr;

    public function findAvail($bal, $dep, $ttlBal){
        echo $this->ttlBal = $bal - $dep;
    }
}
?>

这会导致我无法访问私有属性 $ttlBal 的错误。我可以通过什么方式访问它。

【问题讨论】:

  • 私有属性只对类内的函数可用 创建一个get函数

标签: php private


【解决方案1】:

你应该为你的类添加一个公共的 setter 方法:

class Foo {
    private $var;

    public function setVar($value) {
        $this->var = $value;
    }
}

在许多情况下,如果您使用privateprotected 就是您想要的。如果您只想隐藏该变量以防止公共访问,请使用protected

【讨论】:

    【解决方案2】:

    你的错误在这里$balance-&gt;ttlBal

    要么创建属性public,要么在Customer 类中实现get()set() 方法。

    举个例子

    public function get_ttlBal()
    {
        return $this->ttlBal;
    }
    

    然后你就可以打电话了

    $balance->findAvail($balance->acctBal, $balance->deposits, $balance->get_ttlBal());
    

    【讨论】:

      【解决方案3】:

      要访问以前由 setter 函数设置的私有属性,您应该编写并使用 getter 方法。

      public function getVar() {
          return $this->_var;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-02
        • 1970-01-01
        • 2014-12-10
        • 1970-01-01
        • 2012-04-29
        • 1970-01-01
        • 1970-01-01
        • 2019-11-20
        • 1970-01-01
        相关资源
        最近更新 更多