Skip to content

Allow for-loop for stdClass-objects. - #5000

Closed
antoineveldhoven wants to merge 1 commit into
twigphp:3.xfrom
antoineveldhoven:for-loop-stdClass
Closed

antoineveldhoven wants to merge 1 commit into
twigphp:3.xfrom
antoineveldhoven:for-loop-stdClass

Conversation

@antoineveldhoven

Copy link
Copy Markdown

Aiming to provide a fix for #4999

@fabpot

fabpot commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Thanks for the report and the PR.

This current behavior is intended: the for tag iterates over arrays and Traversable objects only. So stdClass, like any other object, is treated as an empty sequence.

Supporting stdClass would add a special case to every sequence operation and to the sandbox (this PR introduces a security issue), for something easily fixed where the data is created: json_decode($json, true) returns arrays instead of stdClass objects. I've documented this in the for tag docs (#5001), so I'm closing this one.

@fabpot fabpot closed this Oct 19, 2026
@antoineveldhoven

Copy link
Copy Markdown
Author

@fabpot can you elaborate why this would cause a security issue? In plain PHP you can also iterate over properties in stdClass, since they are all "public". For all I know these changes only affect the ForLoop in TwigPHP.
Using the json_decode fix will require that this is done in PHP, when a developer decides to pass a stdClass to a template it will explicitly accept that all the members / properties are exposed.

If I want to access the stdClass I still can do:

<?php
require_once '/path/to/vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('/path/to/templates');
$twig = new \Twig\Environment($loader, [
    'cache' => '/path/to/compilation_cache',
]);

$std_Class = (object) ['obj' => (object) ['key1' => 'one', 'key2' => 'two']];
$template = '
{% set json = std_Class.obj|json_encode|raw|split(",") %}
{% for item in json %}
    {% set pair = item|replace({"\"": ""})|replace({"{": ""})|replace({"}": ""})|split(":") %}
    {{ pair.0 }}: {{ pair.1 }}
{% endfor %}
';

$loader->setTemplate('template', $template);
$output = $twig->render('template', ['std_Class' => $std_Class]));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants