0

I am trying to call a property declared in a constructor in a static method but I don't think I am doing it the right way as I am getting no result. This is my code:

class myClass
{
    private static $client;

    public function __construct(Client $client)
    {
        self::$client = $client;
    }
    public static function getBuses(){
        $call = self::$client->get('localhost/api-call');
    }
}

What might be wrong here? I get this error - Call to a member function get() on null

shekwo
  • 1,411
  • 1
  • 20
  • 50
  • What is `get()` – Zain Farooq Sep 07 '18 at 10:38
  • Do you see errors or what? Static method __has access__ to static properties. – u_mulder Sep 07 '18 at 10:39
  • Possible duplicate of [PHP Class constructor not running when called from static function in another class](https://stackoverflow.com/questions/28993749/php-class-constructor-not-running-when-called-from-static-function-in-another-cl) – Zain Farooq Sep 07 '18 at 10:40
  • "_Error calling a property in a static method_" What error do you get? – brombeer Sep 07 '18 at 10:41
  • 4
    http://sandbox.onlinephpfunctions.com/code/aedc04c5b84fdc27ada7786233ac19d0f4a2fab2 - looks good isn't it ? – Atural Sep 07 '18 at 10:42
  • When the above, I get this error - Call to a member function get() on null – shekwo Sep 07 '18 at 10:47
  • Do you actually instantiate `myClass` before you call `getBuses()`? Constructors are called upon _instantiation_. If you haven't instantiated the class before calling the static method, then the constructor won't have been called and the `$client` variable will be null. – M. Eriksson Sep 07 '18 at 10:48
  • 3
    If your code depends on the constructor to set properties, then you shouldn't use `static` to begin with. – M. Eriksson Sep 07 '18 at 10:50
  • SHow us how you are Instantiating the `myClass` object, ny guess is you are not – RiggsFolly Sep 07 '18 at 10:51
  • `private static $client;` is in memory before the constructor is called. You must assign it a value. – Fabulous Sep 07 '18 at 10:52
  • You guys are right. I didn't instantiate the class. Thanks. Works now. – shekwo Sep 07 '18 at 10:53
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – Mike Doe Sep 07 '18 at 11:50

1 Answers1

-1

This is working for me. Please give us some more code to work with as Client class, or the way you are executing this

<?php
class myClass
{
    private static $client;

    public function __construct(Client $client)
    {
        self::$client = $client;
    }
    public static function getBuses(){
        $call = self::$client->get('localhost/api-call');
        return $call;
    }
}

class Client
{
    public function get($string)
    {
        return $string;
    }
}

$client = new Client();
$class = new myClass($client);
echo $class::getBuses();
FedeCaceres
  • 158
  • 1
  • 11