Skip to content

02.44 The __toString magic method

rafageist edited this page Nov 16, 2026 · 1 revision

2.44 El método mágico __toString

Si un objeto implementa __toString, Div puede tratarlo como una cadena en tres ámbitos: el ámbito de la plantilla, el ámbito del cuerpo de un bucle y el ámbito de una cápsula.

  • Ámbito de la plantilla: $_to_string
  • Ámbitos de bucle y de cápsula: $_to_string y $value

6.44.1 Ejemplo en el ámbito de la plantilla

Person.php

class Person{
    public function __construct($first_name, $last_name){
        $this->first_name = $first_name;
        $this->last_name = $last_name;
    }

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

index.php

include 'div.php';
include 'Person.php';

echo new div('index.tpl', new Person("Albert", "Einstein"));

index.tpl

{$_to_string}

Salida

Albert Einstein

6.44.2 Ejemplo en el ámbito del cuerpo de un bucle

index.php

<?php

include 'div.php';
include 'Person.php';

echo new div('index.tpl', [
    "persons" => [
        new Person("Albert", "Einstein"),
        new Person("John", "Nash")
    ]
]);

index.tpl

If Person does not have a $value property:

[$persons]
    {$value}
[/$persons]

You can always use $_to_string:

[$persons]
    {^^^_to_string}
[/$persons]

Salida

If Person does not have a $value property:

    Albert Einstein
    John Nash

You can always use $_to_string:

    ALBERT EINSTEIN
    JOHN NASH

6.44.3 Ejemplo en el ámbito de una cápsula

index.php

<?php

include 'div.php';
include 'Person.php';

echo new div('index.tpl', [
    "person" => new Person("Albert", "Einstein")
]);

index.tpl

[[person
    {$_to_string}

    {^^^value}

person]]

Salida

Albert Einstein

ALBERT EINSTEIN

Div

Enlaces

Clone this wiki locally