简体   繁体   English

如何在php中访问私有属性,甚至可以?

[英]How to access Private properties in php or even can i?

I have a simple example of code in which i would like to set the private property $ttlBal. 我有一个简单的代码示例,其中我想设置私有属性$ 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;
    }
}
?>

This brings about an error that I cannot access the private property $ttlBal. 这带来了一个错误,我无法访问私有属性$ ttlBal。 In which way can I access this. 我可以通过哪种方式访问​​它。

You should add a public setter method to your class: 您应该在类中添加一个公共的setter方法:

class Foo {
    private $var;

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

Also in many cases protected is what you want if you use private . 同样,在很多情况下,如果使用private想要protected是。 If you just want to hide the variable from public access, use protected . 如果您只想从公共访问中隐藏该变量,请使用protected

Youe error is here $balance->ttlBal 您的错误在这里$balance->ttlBal

Either you will make the property public or you would implement get() and set() methods for it in Customer class. 您可以public该属性,也可以在Customer类中实现该属性的get()set()方法。

As an example 举个例子

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

and then you can call 然后你可以打电话

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

To access private properties, previously set by setter function, you should write and use getter method. 要访问先前由setter函数设置的私有属性,应编写并使用getter方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM