<p>Because <code>MyVar</code> is a service, the easiest solution is to just access it the same way you'd access any other service, e.g.:</p>
<pre><code>$whatever = MyModule::getInstance()-&gt;myVar-&gt;whatever
</code></pre>

CC BY-SA 4.0
2022-12-16T13:00:12.120Z
This does not work. It would require to keep a reference to myVar in MyModule, which works if I'm in control over my module but not for foreign craft.something variables.
Matthias Redl-Mann
CC BY-SA 4.0
2022-12-16T13:02:26.683Z
Let's say I want to access craft.blitz from PHP... (Blitz Cache)
Matthias Redl-Mann
CC BY-SA 4.0
2022-12-17T08:51:42.350Z
OK, at least for Blitz I found out, that you can simply use Blitz::$plugin-> to access the Blitz object.
Matthias Redl-Mann
CC BY-SA 4.0
2022-12-15T08:07:38.007Z
2022-12-15T08:07:38.007Z
Jalen Davenport
<p>We are using a custom variable initalized like this in our module:</p>
<pre><code>    Event::on(CraftVariable::class, CraftVariable::EVENT_INIT,
        function (Event $event) {
            /** @var CraftVariable $variable */
            $variable = $event-&gt;sender;
            $variable-&gt;set('myvar', MyVar::class);
        }
    );
</code></pre>
<p>The variable can be access from TWIG via</p>
<pre><code>    {{ craft.myvar.WHATEVER }}
</code></pre>
<p>But how can I access it from PHP, e.g. from an adjuster or another controller?</p>

<modules><variable><custom>
How to access craft custom variable from PHP
# How to access craft custom variable from PHP

(Asked by: username_0 on 2022-12-15)

We are using a custom variable initalized like this in our module:
    Event::on(CraftVariable::class, CraftVariable::EVENT_INIT,
        function (Event $event) {
            /** @var CraftVariable $variable */
            $variable = $event->sender;
            $variable->set('myvar', MyVar::class);
        }
    );

The variable can be access from TWIG via
    {{ craft.myvar.WHATEVER }}

But how can I access it from PHP, e.g. from an adjuster or another controller?

**Tags:** modules, variable, custom

---

## 1 answers

### Answer by username_1 on 2022-12-15. Score: 1

Because MyVar is a service, the easiest solution is to just access it the same way you'd access any other service, e.g.:
$whatever = MyModule::getInstance()->myVar->whatever

> **Comments:**
> **username_0**: This does not work. It would require to keep a reference to myVar in MyModule, which works if I'm in control over my module but not for foreign craft.something variables.  
> **username_0**: Let's say I want to access craft.blitz from PHP... (Blitz Cache)  
> **username_0**: OK, at least for Blitz I found out, that you can simply use Blitz::$plugin-> to access the Blitz object.  

---

