Magic methods
Demonstrates property interception, dynamic invocation, and string conversion; each language approximates them with different mechanisms.
C C23
#include <stdio.h>
#include <string.h>
typedef struct {
char key[16];
char value[32];
} Pair;
// magic-method idiom: a function-pointer table holds the "interception" entry points
typedef struct {
const char *(*get)(const void *self, const char *key); // approximates __get
const char *(*call)(const void *self, const char *name); // approximates __call
const char *(*to_string)(const void *self); // approximates __toString
} MagicOps;
typedef struct {
const MagicOps *ops;
Pair data[1];
} Person;
static const char *person_get(const void *self, const char *key) {
const Person *p = (const Person *)self;
for (size_t i = 0; i < sizeof(p->data) / sizeof(p->data[0]); i++) {
if (strcmp(p->data[i].key, key) == 0) return p->data[i].value;
}
return "NULL"; // approximates PHP's null
}
static const char *person_call(const void *self, const char *name) {
(void)self;
static char buf[64];
snprintf(buf, sizeof(buf), "called a missing method: %s", name);
return buf;
}
static const char *person_to_string(const void *self) {
const Person *p = (const Person *)self;
static char buf[64];
snprintf(buf, sizeof(buf), "Person(name=%s)", p->data[0].value);
return buf;
}
static const MagicOps person_ops = { person_get, person_call, person_to_string };
int main(void) {
Person p = { &person_ops, { { "name", "Alice" } } };
printf("%s\n", p.ops->get(&p, "name")); // actually enters get("name")
printf("%s\n", p.ops->call(&p, "sayHello")); // actually enters call("sayHello")
printf("%s", p.ops->to_string(&p));
return 0;
}
Alice called a missing method: sayHello Person(name=Alice)
C++ C++26
#include <iostream>
#include <map>
#include <string>
class Person {
public:
// operator[] approximates __get: reads data by key
std::string operator[](const std::string &key) const {
auto it = data_.find(key);
return it != data_.end() ? it->second : "";
}
// C++ has no __call; a plain member function emulates the "missing method" forwarding
std::string call(const std::string &name) const {
return "called a missing method " + name;
}
// operator<< approximates __toString: the ostream output protocol
friend std::ostream& operator<<(std::ostream &os, const Person &p) {
return os << "Person(name=" << p.data_.at("name") << ")";
}
private:
std::map<std::string, std::string> data_ = {{"name", "Alice"}};
};
int main() {
Person p;
std::cout << p["name"] << "\n"; // actually enters operator[]
std::cout << p.call("sayHello") << "\n";
std::cout << p << "\n"; // actually enters operator<<
return 0;
}
Alice called a missing method sayHello Person(name=Alice)
C# v11.0.100
dynamic p = new Person(); // dynamic: member resolution deferred to runtime
Console.WriteLine(p.name);
Console.WriteLine(p.sayHello());
Console.WriteLine(p);
class Person : System.Dynamic.DynamicObject { // DynamicObject approximates PHP's magic methods
private readonly Dictionary<string, object> data = new() { ["name"] = "Alice" };
public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result) {
// fires when reading an undefined property (corresponds to __get)
data.TryGetValue(binder.Name, out result!);
return true;
}
public override bool TryInvokeMember(System.Dynamic.InvokeMemberBinder binder, object?[]? args, out object? result) {
result = $"called a missing method {binder.Name}"; // fires when invoking an undefined method (corresponds to __call)
return true;
}
public override string ToString() => $"Person(name={data["name"]})"; // corresponds to __toString
}
Alice called a missing method sayHello Person(name=Alice)
Go v1.27.4
package main
import "fmt"
// Go has no magic-method system; but fmt recognizes a set of conventional interfaces:
// types implementing fmt.Stringer have their String() called automatically by the fmt family
// (likewise error's Error() and fmt.Formatter go through this mechanism;
// json.Marshaler and friends are recognized by their encoding packages, not by fmt)
type Person struct {
Name string
}
func (p Person) String() string {
return fmt.Sprintf("Person(name=%s)", p.Name)
}
func main() {
p := Person{Name: "Alice"}
fmt.Println(p) // p.String() called automatically
}
Person(name=Alice)
Java v27.0.1
public class Main {
static class Person {
private final String name;
Person(String name) { this.name = name; }
@Override
public String toString() { // println calls it automatically
return "Person(name=" + name + ")";
}
}
public static void main(String[] args) {
Person p = new Person("Alice");
System.out.println(p);
}
}
Person(name=Alice)
JavaScript v26.13.1
// JS has no magic-method concept: getters are explicit syntax, and Proxy can intercept property access
const data = { name: "Alice" };
const p = new Proxy(data, {
get(target, key) {
if (key in target) return target[key];
return `no property ${String(key)}`; // intercepts undefined properties
},
});
class Person {
get name() {
return data.name;
}
}
console.log(new Person().name);
console.log(p.name);
console.log(p.age);
Alice Alice no property age
PHP v8.6.0
class Person {
private array $data = ["name" => "Alice"];
public function __get($key) { // fires when reading an inaccessible/undefined property
return $this->data[$key] ?? null;
}
public function __call($name, $args) { // fires when invoking an undefined method
return "called a missing method $name";
}
public function __toString(): string { // fires in string context
return "Person(name={$this->data['name']})";
}
}
$p = new Person();
echo $p->name, "\n"; // actually enters __get('name')
echo $p->sayHello(), "\n"; // actually enters __call('sayHello', [])
echo $p, "\n"; // actually enters __toString()
Alice called a missing method sayHello Person(name=Alice)
Python v3.15.2
class Person:
def __init__(self):
self._data = {"name": "Alice"}
def __getattr__(self, key): # fires only after normal lookup fails
return self._data.get(key, f"no property {key}")
def __call__(self, *args): # fires when the instance is called like a function
return f"instance invoked with arguments {args}"
def __str__(self): # fires on print/str()
return f"Person(name={self._data['name']})"
p = Person()
print(p.name)
print(p.abc)
print(p(1, 2))
print(p)
Alice no property abc instance invoked with arguments (1, 2) Person(name=Alice)
Rust v1.99.1
// Rust has no magic methods; trait conventions replace them: implement Display for {} formatting
use std::fmt;
struct Person {
name: String,
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Person(name={})", self.name)
}
}
fn main() {
let p = Person { name: String::from("Alice") };
println!("{}", p); // output via the Display trait
}
Person(name=Alice)
TypeScript v26.13.1
// TS has no magic-method concept: getters are explicit syntax, and Proxy can intercept property access
const data = { name: "Alice" };
const p = new Proxy(data, {
get(target, key: string) {
if (key in target) return target[key];
return `no property ${key}`; // intercepts undefined properties
},
});
class Person {
get name(): string {
return data.name;
}
}
console.log(new Person().name);
console.log(p.name);
console.log(p.age);
Alice Alice no property age
Language differences
C: no runtime interception — a function-pointer table dispatches explicitly, mimicking magic methods (triggered by caller convention).
C++: no magic methods — operator overloading expresses __get (operator[]) and __toString (operator<<); there is no __call equivalent, so a plain member function emulates it.
C#: approximates __get/__call by overriding TryGetMember/TryInvokeMember on DynamicObject and binding through dynamic.
Go: the fmt package recognizes conventional interfaces such as fmt.Stringer (String()) and error (Error() — fmt.Println(err) goes through this path), along with fmt.Formatter, json.Marshaler, and others, but has no property/method interception system.
Java: has only a few conventions like toString.
JavaScript: no magic methods — getters/setters are explicitly declared syntax, and Proxy can intercept property access at runtime (as in the example).
PHP: double-underscore magic methods — __get (reads inaccessible or undefined properties), __call (invokes undefined methods), __toString (string contexts).
Python: counterparts are __getattr__ (note: it fires only after normal lookup fails; use __getattribute__ to intercept every access), __call__, __str__, plus many more data-model protocols such as __getitem__/__len__.
Rust: expresses similar capabilities with traits (Display, etc.).