note 126434 added to language.oop5.overloading
| From: | johannes dot kingma at gmail dot com | Date: | Sat, 18 Sep 2021 11:35:04 +0000 |
| Subject: | note 126434 added to language.oop5.overloading | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-216971@lists.php.net to get a copy of this message | ||
One interesting use of the __get function is property / function colaescence, using the same name
for a property and a function.
Example:
<?php
class prop_fun {
private $prop = 123;
public function __get( $property ) {
if( property_exists( $this, $property ) ){
return $this-> $property;
}
throw new Exception( "no such property $property." );
}
public function prop() {
return 456;
}
}
$o = new prop_fun();
echo $o-> prop . '<br>' . PHP_EOL;
echo $o-> prop() . '<br>' . PHP_EOL;
?>
This will output 123 and 456. This does look like a funy cludge but I used it of a class containing
a date type property and function allowing me to write
<?php
class date_class {
/** @property int $date */
private $the_date;
public function __get( $property ) {
if( property_exists( $this, $property ) ){
return $this-> $property;
}
throw new Exception( "no such property $property." );
}
public function the_date( $datetime ) {
return strtotime( $datetime, $this-> the_date );
}
public function __construct() {
$this-> the_date = time();
}
}
$date_object = new date_class();
$today = $date_object-> the_date;
$nextyear = $date_object-> the_date("+1 year");
echo date( "d/m/Y", $today) . '<br>';
echo date( "d/m/Y", $nextyear );
?>
Which I like because its self documenting properties. I used this in a utility class for user input.
----
Server IP: 45.112.84.4
Probable Submitter: 45.112.85.242 (proxied: 83.97.87.182)
----
Manual Page -- https://php.net/manual/en/language.oop5.overloading.php
Edit -- https://main.php.net/note/edit/126434
Del: integrated -- https://main.php.net/note/delete/126434/integrated
Del: useless -- https://main.php.net/note/delete/126434/useless
Del: bad code -- https://main.php.net/note/delete/126434/bad+code
Del: spam -- https://main.php.net/note/delete/126434/spam
Del: non-english -- https://main.php.net/note/delete/126434/non-english
Del: in docs -- https://main.php.net/note/delete/126434/in+docs
Del: other reasons-- https://main.php.net/note/delete/126434
Reject -- https://main.php.net/note/reject/126434
Search -- https://main.php.net/manage/user-notes.php