Suche…


__get (), __set (), __isset () und __unset ()

Wann immer Sie versuchen, ein bestimmtes Feld aus einer Klasse abzurufen:

$animal = new Animal();
$height = $animal->height;

PHP ruft die magische Methode __get($name) , wobei $name in diesem Fall gleich "height" ist. Schreiben Sie so in ein Klassenfeld:

$animal->height = 10;

__set($name, $value) die magische Methode __set($name, $value) , wobei $name "height" und $value 10 .

PHP hat auch zwei eingebaute Funktionen isset() , die prüfen, ob eine Variable existiert, und unset() , wodurch eine Variable zerstört wird. Prüfen, ob ein Objektfeld so eingestellt ist:

isset($animal->height);

__isset($name) die __isset($name) für dieses Objekt auf. Eine Variable wie folgt zerstören:

unset($animal->height);

__unset($name) Funktion __unset($name) für dieses Objekt auf.

Normalerweise ruft PHP, wenn Sie diese Methoden nicht in Ihrer Klasse definieren, das Feld so ab, wie es in Ihrer Klasse gespeichert ist. Sie können diese Methoden jedoch überschreiben, um Klassen zu erstellen, die Daten wie ein Array enthalten können, aber wie ein Objekt verwendet werden können:

class Example {
    private $data = [];

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

    public function __get($name) {
        if (!array_key_exists($name, $this->data)) {
            return null;
        }

        return $this->data[$name];
    }

    public function __isset($name) {
        return isset($this->data[$name]);
    }

    public function __unset($name) {
        unset($this->data[$name]);
    }
}

$example = new Example();

// Stores 'a' in the $data array with value 15
$example->a = 15;

// Retrieves array key 'a' from the $data array
echo $example->a; // prints 15

// Attempt to retrieve non-existent key from the array returns null
echo $example->b; // prints nothing

// If __isset('a') returns true, then call __unset('a')
if (isset($example->a)) {
    unset($example->a));
}

leere () Funktion und magische Methoden

Beachten Sie, dass beim Aufruf von empty() für ein Klassenattribut __isset() wird, da das PHP-Handbuch __isset() besagt:

empty () ist im Wesentlichen das knappe Äquivalent zu ! isset ($ var) || $ var == false

__construct () und __destruct ()

__construct() ist die am häufigsten verwendete Zaubermethode in PHP, da sie zum Einrichten einer Klasse verwendet wird, wenn sie initialisiert wird. Das Gegenteil der __construct() -Methode ist die __destruct() -Methode. Diese Methode wird aufgerufen, wenn keine Verweise auf ein von Ihnen erstelltes Objekt mehr vorhanden sind oder wenn Sie das Löschen erzwingen. Die Garbage Collection von PHP bereinigt das Objekt, indem es zuerst seinen Destruktor aufruft und es dann aus dem Speicher entfernt.

class Shape {
    public function __construct() {
        echo "Shape created!\n";
    }
}

class Rectangle extends Shape {
    public $width;
    public $height;

    public function __construct($width, $height) {
        parent::__construct();

        $this->width = $width;
        $this->height = $height;
        echo "Created {$this->width}x{$this->height} Rectangle\n"; 
    }

    public function __destruct() {
        echo "Destroying {$this->width}x{$this->height} Rectangle\n";
    }
}

function createRectangle() {
    // Instantiating an object will call the constructor with the specified arguments
    $rectangle = new Rectangle(20, 50);

    // 'Shape Created' will be printed
    // 'Created 20x50 Rectangle' will be printed
}

createRectangle();
// 'Destroying 20x50 Rectangle' will be printed, because
// the `$rectangle` object was local to the createRectangle function, so
// When the function scope is exited, the object is destroyed and its
// destructor is called.

// The destructor of an object is also called when unset is used:
unset(new Rectangle(20, 50));

__toString ()

Wenn ein Objekt als Zeichenfolge behandelt wird, wird die Methode __toString() aufgerufen. Diese Methode sollte eine Zeichenfolgendarstellung der Klasse zurückgeben.

class User {
    public $first_name;
    public $last_name;
    public $age;

    public function __toString() {
        return "{$this->first_name} {$this->last_name} ($this->age)";
    }
}

$user = new User();
$user->first_name = "Chuck";
$user->last_name = "Norris";
$user->age = 76;

// Anytime the $user object is used in a string context, __toString() is called

echo $user; // prints 'Chuck Norris (76)'

// String value becomes: 'Selected user: Chuck Norris (76)'
$selected_user_string = sprintf("Selected user: %s", $user);

// Casting to string also calls __toString()
$user_as_string = (string) $user;

__aufrufen()

Diese magische Methode wird aufgerufen, wenn der Benutzer versucht, ein Objekt als Funktion aufzurufen. Mögliche Anwendungsfälle können einige Ansätze wie die funktionale Programmierung oder einige Rückrufe umfassen.

class Invokable
{
    /**
     * This method will be called if object will be executed like a function:
     *
     * $invokable();
     *
     * Args will be passed as in regular method call.
     */
    public function __invoke($arg, $arg, ...)
    {
        print_r(func_get_args());
    }
}

// Example:
$invokable = new Invokable();
$invokable([1, 2, 3]);

// optputs:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

__call () und __callStatic ()

__call() und __callStatic() werden aufgerufen, wenn jemand eine nicht vorhandene Objektmethode im Objekt oder statischen Kontext aufruft.

class Foo
{
    /**
     * This method will be called when somebody will try to invoke a method in object
     * context, which does not exist, like:
     *
     * $foo->method($arg, $arg1);
     *
     * First argument will contain the method name(in example above it will be "method"),
     * and the second will contain the values of $arg and $arg1 as an array.
     */
    public function __call($method, $arguments)
    {
        // do something with that information here, like overloading
        // or something generic.
        // For sake of example let's say we're making a generic class,
        // that holds some data and allows user to get/set/has via
        // getter/setter methods. Also let's assume that there is some
        // CaseHelper which helps to convert camelCase into snake_case.
        // Also this method is simplified, so it does not check if there
        // is a valid name or
        $snakeName = CaseHelper::camelToSnake($method);
        // Get get/set/has prefix
        $subMethod = substr($snakeName, 0, 3);

        // Drop method name.
        $propertyName = substr($snakeName, 4);

        switch ($subMethod) {
            case "get":
                return $this->data[$propertyName];
            case "set":
                $this->data[$propertyName] = $arguments[0];
                break;
            case "has":
                return isset($this->data[$propertyName]);
            default:
                throw new BadMethodCallException("Undefined method $method");
        }
    }

    /**
     * __callStatic will be called from static content, that is, when calling a nonexistent
     * static method:
     *
     * Foo::buildSomethingCool($arg);
     *
     * First argument will contain the method name(in example above it will be "buildSomethingCool"),
     * and the second will contain the value $arg in an array.
     *
     * Note that signature of this method is different(requires static keyword). This method was not
     * available prior PHP 5.3
     */
    public static function __callStatic($method, $arguments)
    {
        // This method can be used when you need something like generic factory
        // or something else(to be honest use case for this is not so clear to me).
        print_r(func_get_args());
    }
}

Beispiel:

$instance = new Foo();

$instance->setSomeState("foo");
var_dump($instance->hasSomeState());      // bool(true)
var_dump($instance->getSomeState());      // string "foo"

Foo::exampleStaticCall("test");
// outputs:
Array
(
    [0] => exampleCallStatic
    [1] => test
)

__sleep () und __wakeup ()

__sleep und __wakeup sind Methoden, die sich auf den Serialisierungsprozess beziehen. serialize Funktion serialize prüft, ob eine Klasse eine __sleep Methode hat. Wenn ja, wird es vor der Serialisierung ausgeführt. __sleep soll ein Array mit den Namen aller Variablen eines Objekts zurückgeben, die serialisiert werden sollen.

__wakeup wiederum von unserialize wenn es in der Klasse vorhanden ist. Es ist beabsichtigt, Ressourcen und andere Dinge wiederherzustellen, die bei der Desialisierung initialisiert werden müssen.

class Sleepy {
    public $tableName;
    public $tableFields;
    public $dbConnection;

    /**
     * This magic method will be invoked by serialize function.
     * Note that $dbConnection is excluded.
     */
    public function __sleep()
    {
        // Only $this->tableName and $this->tableFields will be serialized.
        return ['tableName', 'tableFields'];
    }

    /**
     * This magic method will be called by unserialize function.
     *
     * For sake of example, lets assume that $this->c, which was not serialized,
     * is some kind of a database connection. So on wake up it will get reconnected.
     */
    public function __wakeup()
    {
        // Connect to some default database and store handler/wrapper returned into
        // $this->dbConnection
        $this->dbConnection = DB::connect();
    }
}

__Debug-Informationen()

Diese Methode wird von var_dump() aufgerufen, wenn ein Objekt var_dump() , um die Eigenschaften var_dump() , die angezeigt werden sollen. Wenn die Methode nicht für ein Objekt definiert ist, werden alle öffentlichen, geschützten und privaten Eigenschaften angezeigt. - PHP-Handbuch

class DeepThought {
    public function __debugInfo() {
        return [42];
    }
}
5.6
var_dump(new DeepThought());

Das obige Beispiel gibt Folgendes aus:

class DeepThought#1 (0) {
}
5.6
var_dump(new DeepThought());

Das obige Beispiel gibt Folgendes aus:

class DeepThought#1 (1) {
  public ${0} =>
  int(42)
}

__Klon()

__clone wird mit dem Schlüsselwort clone aufgerufen. Es wird verwendet, um den Objektstatus beim Klonen zu ändern, nachdem das Objekt tatsächlich geklont wurde.

class CloneableUser
{
    public $name;
    public $lastName;

    /**
     * This method will be invoked by a clone operator and will prepend "Copy " to the
     * name and lastName properties.
     */
    public function __clone()
    {
        $this->name = "Copy " . $this->name;
        $this->lastName = "Copy " . $this->lastName;
    }
}

Beispiel:

$user1 = new CloneableUser();
$user1->name = "John";
$user1->lastName = "Doe";

$user2 = clone $user1; // triggers the __clone magic method

echo $user2->name;     // Copy John
echo $user2->lastName; // Copy Doe


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow