mightyspaj3
mightyspaj3

Reputation: 471

PHP OOP - Accessing property value is returning empty

I have the following class, and for some reason it's not accessing the test property. Why is this? I'm new to OOP, so please be easy on me. Thanks

class Test {
    private $test;

    function __contruct() {
        $this->test = "test";
    }

    static function test() {
        echo $this->test;
    }
}

$test = new Test;
$test::test();

Upvotes: 1

Views: 110

Answers (3)

The General
The General

Reputation: 1359

To elaborate further on the above answers: Static methods and variables are not linked to any particular instance of the object, this is why you have to call test with $test::test(). This also means that you cannot access an instance variable from without a static method and it doesn't really make sense to do so (If you had multiple instances of the object with different values set for that variable, how would the interpreter know which instance/value to use?)

If you want to have a field accessible from a static method then you have to make the field static as well. So, if you wanted to have $test accessible from your static method test() then you'd have to write your function as something along these lines:

class Test {
    private static $test;

    function __contruct() {
        Test::$test = "test";
    }

    public function test() {
        echo Test::$test;
    }
}

$test = new Test;
$test::test();

However, it doesn't really make sense to be initialising a static field like that in your constructor. So you'd more likely be wanting to do something like:

class Test {
    private static $test = "test";

    function __contruct() {
    }

    public static function test() {
        echo Test::$test;
    }
}

$test = new Test;
$test::test();

Or, if you don't actually require test() to be static then you could just make it an instance method:

class Test {
    private $test = "test";

    function __contruct() {
        $this->$test = "test"
    }

    public function test() {
        echo $this->$test;
    }
}

$test = new Test;
$test->test();

Upvotes: 0

T Karropoulos
T Karropoulos

Reputation: 61

Good morning. It seems you have 3 issues with your code.

  1. There is a syntax error at constructor line change it from __contruct to __construct.
  2. Change test function visibility to public
  3. Access your function with the -> instead of ::

Upvotes: 0

someOne
someOne

Reputation: 1675

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

PHP Documentations.

Upvotes: 3

Related Questions