Created
March 15, 2024 19:27
-
-
Save thinkstylestudio/890b2d360fb418b6dbdab037df681746 to your computer and use it in GitHub Desktop.
Example of watcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//dilo surucu | |
#[AllowDynamicProperties] | |
/** | |
* @property string $name | |
*/ | |
class Person | |
{ | |
private array $properties = []; | |
private array $watches = []; | |
/** | |
* @param string $propertyName | |
* @param Closure(mixed $oldValue,mixed $newValue):void $closure() | |
* @return void | |
*/ | |
public function watch(string $propertyName,Closure $closure):void | |
{ | |
$this->watches[$propertyName] = $closure; | |
} | |
public function __set(string $name, $value): void | |
{ | |
if (isset($this->watches[$name])) { | |
$oldValue = $this->properties[$name] ?? null; | |
$this->properties[$name] = $value; | |
$this->watches[$name]($oldValue, $value); | |
} | |
} | |
public function __get(string $name):string | |
{ | |
return $this->properties[$name]; | |
} | |
} | |
$person = new Person(); | |
$person->watch('name', function ($oldValue, $newValue){ | |
echo "[$oldValue,$newValue]".PHP_EOL; | |
}); | |
$person->name = 'dilo'; | |
$person->name = 'alex'; | |
$person->name = 'john'; | |
echo $person->name; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment