Pyh.conf’25: a new PHP conference for the Russian-speaking community

Voting

: min(six, three)?
(Example: nine)

The Note You're Voting On

johannes dot kingma at gmail dot com
3 years ago
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.

<< Back to user notes page

To Top