Global variable created in a function is not recognized by code completion

Hello, I'm evaluating phpstorm 5.0.2 and I found a problem with one project.

I have a situation where i have a global variable (database instance)  that is initialized in an init function and the code completion does not  work on the global var.

This small example shows the problem

<?php
    class dbhandler {
        function query() {
        }
    }




    function init() {
        global $gDB ;
        $gDB = new dbhandler();
    }




    $gDB->

When i put the cursor after the -> in the last line there is no code completion.

If I move the declaration outside of the function then everything works.

Is it possible to handle this behaviour ?

4 comments
Comment actions Permalink

Hi Daniele,

You can use this approach: declare that variable in global scope with null value with adding proper PHPDoc to it.

<?php

/** @var dbhandler $gDB My DB handler (or whatever optional description you want to give it) */
$gDB = null;

// continue as usual...



class dbhandler {
...

0
Comment actions Permalink

Another possible approach would be to use pure static class that would hold all of such global variables and instead of referring to global variable you refer to variable in that class. From IDE point of view it is more easier to process. From your point of view it could be too much hassle to change existing code + possible other things (that single static class may simply not be suitable for).

<?php
class MyApp
{
     /** @var dbhandler DB Handler (or other optional description) */
     public static $gDB;
}


class dbhandler
{


    function query()
    {
    }
}


function init()
{
    MyApp::$gDB = new dbhandler();
}


MyApp::$gDB->


But generally speaking you should avoid global variables if possible -- this would make your code more portable/reusable and easier to debug (and especially test -- unit testing).

0
Comment actions Permalink

This works well, thanks for the help.

0
Comment actions Permalink

Yes I know, but it's an old project written with php3 and still in use.

I will also consider the static class.

Thanks

Daniele

0

Please sign in to leave a comment.