<p>Twig doesn't have a native "instanceof" check, but it'd be pretty trivial to create a <a href="https://pluginfactory.io/" rel="nofollow noreferrer">simple plugin</a> that added a Twig Extension where you can add an <a href="https://secure.php.net/manual/en/internals2.opcodes.instanceof.php" rel="nofollow noreferrer">instanceof</a> test.</p>

<pre><code>public function getTests()
{
    return array(
        'instanceof' =&gt;  new \Twig_Function_Method($this, 'isInstanceof')
    );
}

public function isInstanceof($var, $instance)
{
    return  $var instanceof $instance;
}
</code></pre>

<p>Then from your template, you'd do something like:</p>

<pre><code>{% if value is instanceof('Commerce_ProductModel') %}
</code></pre>

CC BY-SA 3.0
2017-08-17T21:44:45.017Z
Thanks Brad, I was hoping for a solution in Twig but this will do nicely!
amogower
CC BY-SA 3.0
2017-08-17T19:18:07.320Z
2017-08-17T19:18:07.320Z
Brad Bell
<p>When querying multiple model types (entries, Commerce products and Commerce variants) I want to be able to detect the model type of each item as I iterate over the results array.</p>

<p>Ideally to avoid this sort of error:</p>

<pre><code>Craft\EntryModel and its behaviors do not have a method or closure named
</code></pre>

<p>There doesn't seem to be a clean way of doing this but I may be wrong!</p>

CC BY-SA 3.0
2017-08-16T19:27:58.253Z
Are you doing this from PHP or from Twig?
Brad Bell
CC BY-SA 3.0
2017-08-16T22:52:59.577Z
From Twig, hence the confusion...
amogower
<plugin-craftcommerce><entrymodel><models>
How to detect the model type of an item in an array of query results
# How to detect the model type of an item in an array of query results

(Asked by: username_0 on 2017-08-16)

When querying multiple model types (entries, Commerce products and Commerce variants) I want to be able to detect the model type of each item as I iterate over the results array.
Ideally to avoid this sort of error:
Craft\EntryModel and its behaviors do not have a method or closure named

There doesn't seem to be a clean way of doing this but I may be wrong!

**Tags:** plugin-craftcommerce, entrymodel, models

> **Comments:**
> **username_1**: Are you doing this from PHP or from Twig?  
> **username_0**: From Twig, hence the confusion...  

---

## 1 answers

### Answer by username_1 on 2017-08-17. Score: 0 | Accepted answer

Twig doesn't have a native "instanceof" check, but it'd be pretty trivial to create a simple plugin that added a Twig Extension where you can add an instanceof test.
public function getTests()
{
    return array(
        'instanceof' =>  new \Twig_Function_Method($this, 'isInstanceof')
    );
}

public function isInstanceof($var, $instance)
{
    return  $var instanceof $instance;
}

Then from your template, you'd do something like:
{% if value is instanceof('Commerce_ProductModel') %}

> **Comments:**
> **username_0**: Thanks Brad, I was hoping for a solution in Twig but this will do nicely!  

---

