Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sos99's avatar
Level 7

How to call a class only once (global variable scope)

on clean project in php (without framework), i have class that i need available in all classes (for example log, db) , what is the best OOP way to do it available without global variable or call to new object all the time ?

https://stackoverflow.com/questions/28730071/have-only-one-instance-of-a-class

https://stackoverflow.com/questions/3695663/functions-that-can-be-called-only-once

https://wordpress.stackexchange.com/questions/45648/how-to-call-a-function-only-once-global-variable-scope

0 likes
5 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

Write a static helper.

In cakephp I wanted to use session in a static class method, but I had to do a small work around:

<?php

namespace App\Helpers;

use Cake\Http\Session;

class SessionHelper
{
    public static function __callStatic($method, $params)
    {
        $instance = Session::class;
        $c = new $instance;
        return $c->$method(...array_values($params));
    }
}

So in my static method I could then use:

$usersession = session::read('loggin');

Static methods are usually fine for direct calls, a simple use statement:

use App\Helpers\SessionHelper as session;

And the static class with methods are available, none of that new and $this all over.

That's why Taylor has facades, for an expressive good looking syntax.

In cake you have:

$this->getRequest()->getSession()->write('psch', $psch);

I said gees, how many arrows do you need.

This:

session::read('loggin');

is just plain prettier. But I only needed that in my static methods, $this is not allowed.

1 like
sos99's avatar
Level 7

this is very nice and helpful but how i prevent calling the new $instance every time ?

jlrdw's avatar

I was talking about having some static methods.

Modern Frameworks don't work the way you think they do. Laravel actually boots on each request as an example.

I would not worry about calling a class one time it's used and disposed of as needed.

I'm just saying there are times when static methods are better.

They are quick use as needed methods. And they are perfect for helper type classes.

1 like

Please or to participate in this conversation.