PHP Magic Methods

<?php class Test { public function __set($key, $value = null) { $this->{$key} = $value; } public function __get($key) { return $this->{$key} ?? false; } public function __invoke($value) { return '__invoke called with ' . $value; } public function __toString() { return 'this is the string version of instance'; } public function __call($key, $arguments) { return '__call called!'; } public static function __callStatic($key, $arguments) { return '__callStatic called!'; } } /* $test = new Test; var_dump( $test, // as instance $test->foo, // test for `__get` $test('foo'), // test for `__invoke` $test->foo(), // test for `__call` $test::foo(), // test for `__callStatic` ); echo $test; // test for `__toString` $test->bar = 20; // test for `__set` echo $test->bar; */

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.