note 112573 rejected from language.references.pass by googleguy
| From: | googleguy@php.net | Date: | Mon, 01 Jul 2013 08:34:21 +0000 |
| Subject: | note 112573 rejected from language.references.pass by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-195417@lists.php.net to get a copy of this message | ||
Note Submitter: akm16 dot ua at gmail dot com
----
ByRef vs. protected and private properties in classes
<?php
class NotProtected {
public $one = 1;
private $two = 2;
protected $three = 3;
function getNum() {
return array(
'one' => &$this->one,
'two' => &$this->two,
'three' => &$this->three
);
}
function change() {
$this->one++;
$this->two++;
$this->three++;
}
}
$obj = new NotProtected();
// Save public, private and protected properties into one array
$a = $obj->getNum();
echo '<pre>';
// Display current state of saved data in variable $a and variables in our class
echo '$a => ' . print_r($a, true);
echo '$obj->getNum() => ' . print_r($obj->getNum(), true);
// Changing variable values in our class by class method
$obj->change();
// Display current state of saved data in variable $a and variables in our class
echo '$a => ' . print_r($a, true);
echo '$obj->getNum() => ' . print_r($obj->getNum(), true);
// Now trying change variable values outside of our class
$a['one'] = 'I`m not One!';
$a['two'] = 'I`m not Two!';
$a['three'] = 'I`m not Three!';
// Display current state of saved data in variable $a and variables in our class
echo '$a => ' . print_r($a, true);
echo '$obj->getNum() => ' . print_r($obj->getNum(), true);
?>
Outputs:
$a => Array
(
[one] => 1
[two] => 2
[three] => 3
)
$obj->getNum() => Array
(
[one] => 1
[two] => 2
[three] => 3
)
$a => Array
(
[one] => 2
[two] => 3
[three] => 4
)
$obj->getNum() => Array
(
[one] => 2
[two] => 3
[three] => 4
)
$a => Array
(
[one] => I`m not One!
[two] => I`m not Two!
[three] => I`m not Three!
)
$obj->getNum() => Array
(
[one] => I`m not One!
[two] => I`m not Two!
[three] => I`m not Three!
)