0

After trying several attempts at this for some reason i get the error Access to undeclared static property when i try to make an object out my class.

My class:

final class repo {
    var $b;

    /**
     * @var \Guzzle\Http\Client
     */
    protected $client;

    function repo($myvar)
    {
        static::$b = $myvar;
        $this->client = $b;
    }
}

Me making an object:

$myobj = new repo("test");
Jimmy KA
  • 9
  • 1
  • 1
  • 2

3 Answers3

0

You should declare $b as static variable.

Also note that method as a class name is deprecated now see the details here

final class repo {
    public static $b;

    /**
     * @var \Guzzle\Http\Client
     */
    protected $client;

    function repo($myvar)
    {
        static::$b = $myvar;
        $this->client = static::$b;
    }
}
TIGER
  • 2,864
  • 5
  • 35
  • 45
0

The declaration var $b; is PHP 4. PHP 5 allows it and it is equivalent to public $b;.

However, it is deprecated and if you use a proper error reporting (error_reporting(E_ALL); during development) you get a warning about it. You should use the PHP 5 visibility kewords instead.

Also, the declaration function repo($myvar) is a PHP 4 constructor style, also accepted but deprecated. You should use the PHP 5 __constructor() syntax.

You access $b as static::$b and this is not compatible with its declaration (equivalent, as I said above, with public $b). If you want it to be a class property (this is what static does) you have to declare it as a class property (i.e. public static $b).

Putting everything together, the proper way to write your class is:

final class repo {
    // public static members are global variables; avoid making them public
    /** @var \Guzzle\Http\Client */
    private static $b;

    // since the class is final, "protected" is the same as "private"
    /** @var \Guzzle\Http\Client */
    protected $client;

    // PHP 5 constructor. public to allow the class to be instantiated.
    // $myvar is probably a \Guzzle\Http\Client object
    public __construct(\Guzzle\Http\Client $myvar)
    {
        static::$b = $myvar;
        // $this->b probably works but static::$b is more clear
        // because $b is a class property not an instance property
        $this->client = static::$b;
    }
}
axiac
  • 68,258
  • 9
  • 99
  • 134
0

Try this

final class repo {
    public $b;

    /**
     * @var \Guzzle\Http\Client
     */
    protected $client;

    function repo($myvar)
    {
        $this->b = $myvar;
        $this->client = $this->b;
    }
}

Note: static::/self:: is used on static functions.

Fahadi Muhumuza
  • 131
  • 1
  • 5