added a tip about dynamic properties
authorfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Thu, 5 Nov 2009 17:42:55 +0000 (17:42 +0000)
committerfabien <fabien@93ef8e89-cb99-4229-a87c-7fa0fa45744b>
Thu, 5 Nov 2009 17:42:55 +0000 (17:42 +0000)
git-svn-id: http://svn.twig-project.org/trunk@114 93ef8e89-cb99-4229-a87c-7fa0fa45744b

doc/02-Twig-for-Template-Designers.markdown
doc/06-Recipes.markdown

index 6ae9b3c..544f8d4 100644 (file)
@@ -70,6 +70,7 @@ If a variable or attribute does not exist you will get back a `null` value.
 >the PHP layer:
 >
 > * check if `foo` is an array and `bar` a valid element;
+> * if not, and if `foo` is an object, check that `bar` is a valid property;
 > * if not, and if `foo` is an object, check that `bar` is a valid method;
 > * if not, and if `foo` is an object, check that `getBar` is a valid method;
 > * if not, return a `null` value.
index 0acd3f1..f1812d6 100644 (file)
@@ -100,3 +100,37 @@ syntax:
       'tag_block'    => array('{', '}'),
       'tag_variable' => array('{$', '}'),
     ));
+
+Using dynamic Object Properties
+-------------------------------
+
+When Twig encounters a variable like `article.title`, it tries to find a
+`title` public property in the `article` object.
+
+It also works if the property does not exist but is rather defined dynamically
+thanks to the magic `__get()` method; you just need to also implement the
+`__isset()` magic method like shown in the following snippet of code:
+
+    [php]
+    class Article
+    {
+      public function __get($name)
+      {
+        if ('title' == $name)
+        {
+          return 'The title';
+        }
+
+        // throw some kind of error
+      }
+
+      public function __isset($name)
+      {
+        if ('title' == $name)
+        {
+          return true;
+        }
+
+        return false;
+      }
+    }