PHP.GT

Getting started

1. Install the package

composer require phpgt/propfunc

2. Import the trait

use GT\PropFunc\MagicProp;

3. Create a class that uses the trait

class User {
	use MagicProp;
}

At this point nothing is exposed yet. The trait is ready to respond to unknown or inaccessible properties, but we still need to define what those properties should do.

4. Add a getter method

class User {
	use MagicProp;

	private string $name = "Cody";

	private function __propGetName():string {
		return $this->name;
	}
}

The method name matters:

  • property name: name
  • getter method: __propGetName

The property part is converted with ucfirst(), so fullName becomes __propGetFullName.

5. Use the class like a normal property API

$user = new User();
echo $user->name;

Even though name is private, the trait notices the property access, finds __propGetName(), calls it, and returns the result.

6. Add a setter when the property should be writable

class User {
	use MagicProp;

	private string $name = "Cody";

	private function __propGetName():string {
		return $this->name;
	}

	private function __propSetName(string $name):void {
		$this->name = trim($name);
	}
}

Now this works:

$user = new User();
$user->name = "  Ada  ";
echo $user->name; // Ada

7. Know what happens when a method is missing

  • If a getter exists but no setter exists, the property is read-only.
  • If no getter or setter exists for that property, a PropertyDoesNotExistException is thrown.

Next, move on to Exceptions and edge cases for handling errors.