Skip to content

Instantly share code, notes, and snippets.

@thinkstylestudio
Created March 15, 2024 19:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thinkstylestudio/890b2d360fb418b6dbdab037df681746 to your computer and use it in GitHub Desktop.
Save thinkstylestudio/890b2d360fb418b6dbdab037df681746 to your computer and use it in GitHub Desktop.
Example of watcher
<?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