Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

PHP Dictionary

  1. Home
  2. PHP Dictionary
  3. trait / Magic Methods

trait / Magic Methods Since: PHP 5.4(2012)

Traits let you define reusable methods that can be mixed into classes. Magic methods give you control over special object behaviors.

Syntax

// Define a trait.
trait TraitName {
	public function method() { }
}

// Mix the trait into a class.
class ClassName {
	use TraitName;
}

// Check an object's type with instanceof.
$obj instanceof ClassName;

Syntax reference

SyntaxDescription
traitDefines a reusable group of methods. Use it in a class with use to share methods across classes without the limitations of single inheritance.
useMixes a trait into a class. You can include multiple traits at once by separating them with commas.
instanceofChecks whether an object is an instance of a given class or interface. Returns true or false.

Common magic methods

MethodDescription
__toString()Called automatically when an object is used as a string, such as with echo $obj;.
__get($name)Called when reading a property that does not exist or is inaccessible.
__set($name, $value)Called when assigning a value to a property that does not exist or is inaccessible.
__call($name, $args)Called when invoking a method that does not exist or is inaccessible.
__invoke(...$args)Called when an object is used like a function, as in $obj().
__clone()Called when an object is duplicated with clone. Use it when you need a deep copy.

Sample code

<?php
// Basic trait usage.
trait Timestampable {
	private string $created_at;
	private string $updated_at;

	public function set_timestamps(): void {
		$now = date('Y-m-d H:i:s');
		$this->created_at = $this->created_at ?? $now;
		$this->updated_at = $now;
	}

	public function get_created_at(): string {
		return $this->created_at;
	}
}

trait SoftDeletable {
	private ?string $deleted_at = null;

	public function soft_delete(): void {
		$this->deleted_at = date('Y-m-d H:i:s');
	}

	public function is_deleted(): bool {
		return $this->deleted_at !== null;
	}
}

// Using multiple traits together.
class Post {
	use Timestampable, SoftDeletable;

	public function __construct(
		public string $title
	) {
		$this->set_timestamps();
	}
}

$post = new Post("Intro to PHP Traits");
echo $post->get_created_at(); // Outputs the current date and time.
$post->soft_delete();
var_dump($post->is_deleted()); // Outputs 'bool(true)'.

// Example of the __toString() magic method.
class Money {
	public function __construct(
		private int $amount,
		private string $currency = 'USD'
	) {}

	public function __toString(): string {
		return number_format($this->amount) . $this->currency;
	}
}

$price = new Money(2980);
echo $price; // Outputs '2,980USD'. __toString() is called automatically.

// Example of __get() and __set().
class FlexibleObject {
	private array $data = [];

	public function __get(string $name): mixed {
		return $this->data[$name] ?? null;
	}

	public function __set(string $name, mixed $value): void {
		$this->data[$name] = $value;
	}
}

$obj = new FlexibleObject();
$obj->color = "red";  // __set() is called.
echo $obj->color;     // __get() is called, outputs 'red'.

// Example of __invoke().
class Multiplier {
	public function __construct(
		private int $factor
	) {}

	public function __invoke(int $value): int {
		return $value * $this->factor;
	}
}

$double = new Multiplier(2);
echo $double(5);  // Outputs '10'. The object is called like a function.
echo $double(15); // Outputs '30'.

// Checking types with instanceof.
var_dump($post instanceof Post);          // Outputs 'bool(true)'.
var_dump($price instanceof Money);        // Outputs 'bool(true)'.
var_dump($price instanceof \Stringable);  // Outputs 'bool(true)' because __toString() is defined.

Overview

Traits were introduced in PHP 5.4 as a way to reuse code across classes. Because PHP supports only single inheritance, a class cannot inherit from multiple parent classes — but traits let you freely mix in multiple sets of functionality. They are well suited for common behaviors shared across many classes, such as managing timestamps, soft deletes, or logging.

Magic methods are special methods that PHP calls automatically in specific situations. __toString() defines the string representation of an object. __get() and __set() control dynamic property access. Defining __invoke() lets you call an object like a function, which is handy when passing it as a callback.

For the basics of classes, see class. For inheritance and interfaces, see extends / implements.

If you find any errors or copyright issues, please .