note 75290 added to language.oop5.visibility
| From: | ference at super_delete_brose dot co dot uk | Date: | Tue, 22 May 2007 17:10:09 +0000 |
| Subject: | note 75290 added to language.oop5.visibility | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-126823@lists.php.net to get a copy of this message | ||
Sometimes you may wish to have all members of a class visible to other classes, but not editable -
effectively read-only.
In this case defining them as public or protected is no good, but defining them as private is too
strict and by convention requires you to write accessor functions.
Here is the lazy way, using one get function for accessing any of the variables:
<?php
class Foo {
private $a;
private $b;
private $c;
private $d;
private $e;
private $f;
public function __construct() {
$this->a = 'Value of $a';
$this->b = 'Value of $b';
$this->c = 'Value of $c';
$this->d = 'Value of $d';
$this->e = 'Value of $e';
$this->f = 'Value of $f';
}
/* Accessor for all class variables. */
public function get($what) {
$result = FALSE;
$vars = array_keys(get_class_vars('Foo'));
foreach ($vars as $var) {
if ($what == $var) {
eval('$result = $this->'.$var.';');
return $result;
}
}
return $result;
}
}
class Bar {
private $a;
public function __construct() {
$foo = new Foo();
var_dump($foo->get('a')); // results in: string(11) "Value of $a"
}
}
$bar = new Bar();
?>
----
Server IP: 81.92.200.26
Probable Submitter: 87.196.104.144
----
Manual Page -- http://www.php.net/manual/en/language.oop5.visibility.php
Edit -- https://master.php.net/note/edit/75290
Del: integrated -- https://master.php.net/note/delete/75290/integrated
Del: useless -- https://master.php.net/note/delete/75290/useless
Del: bad code -- https://master.php.net/note/delete/75290/bad+code
Del: spam -- https://master.php.net/note/delete/75290/spam
Del: non-english -- https://master.php.net/note/delete/75290/non-english
Del: in docs -- https://master.php.net/note/delete/75290/in+docs
Del: other reasons-- https://master.php.net/note/delete/75290
Reject -- https://master.php.net/note/reject/75290
Search -- https://master.php.net/manage/user-notes.php