|
|
|
#1 |
|
Messages: n/a
Hébergeur: |
PHP version 5.2.3
Below you see some .NET code. This is a class contain a private member variable. For other classes to access this private variable they have to use the public method. I'm wondering if something similar is possible with object-oriented PHP (5.2.3) programming?? class Period { private double _second; public double Seconds { get { return _second; } set { _second = value; } } } |
|
|
|
#2 |
|
Messages: n/a
Hébergeur: |
On Sun, 29 Jul 2007 18:53:24 +0200, Jeff
<it_consultant1@hotmail.com.NOSPAM> wrote: > PHP version 5.2.3 > Below you see some .NET code. This is a class contain a private member > variable. For other classes to access this private variable they have to > use > the public method. I'm wondering if something similar is possible with > object-oriented PHP (5.2.3) programming?? > > class Period > { > private double _second; > public double Seconds > { > get { return _second; } > set { _second = value; } > } > } > > An implementation of this could be: <?php class Period{ private $_second; function __set($name,$value){ echo 'Setting '.$name; $this->$name = $value; } function __get($name){ echo 'Getting '.$name; if(isset($this->$name)) return $this->$name; echo 'No such property: Period::'.$name; } } $foo = new Period(); $foo->_second = 123; echo $foo->_second ; ?> Check the manual for the __get()/__set() functions. If you want to force the variable to be a float (or whatever you want) you can enforce that in the __set() method. <http://nl3.php.net/manual/en/language.oop5.overloading.php> -- Rik Wasmus |
|
|
|
#3 |
|
Messages: n/a
Hébergeur: |
On 29 Jul, 18:08, Rik <luiheidsgoe...@hotmail.com> wrote:
> On Sun, 29 Jul 2007 18:53:24 +0200, Jeff > > > > <it_consulta...@hotmail.com.NOSPAM> wrote: > > I'm wondering if something similar is possible with > > object-oriented PHP (5.2.3) programming?? > > > > An implementation of this could be: > > <?php > class Period{ > private $_second; > > function __set($name,$value){ > echo 'Setting '.$name; > $this->$name = $value; > } > function __get($name){ > echo 'Getting '.$name; > if(isset($this->$name)) return $this->$name; > echo 'No such property: Period::'.$name; > }} > > $foo = new Period(); > $foo->_second = 123; > echo $foo->_second ; > ?> Which neatly demonstrates PHPs built in methods for objects - but is probably overkill as a solution to the problem. I don't really know .NET but I suspect this class stores a value and when a new value is set it returns the previous value. In which case: class Period { private $_second; function Seconds($value) { $prev=$this->_second; $this->_second=(double)$value; return($prev); } } C. |
|
![]() |
| Outils de la discussion | |
|
|