DaedalusAlpha
DaedalusAlpha

Reputation: 1727

Access of variable in a null php class

Say that I have a class like this:

class MyClass {
    public $variable;

    public function __construct($variable) {
        $this->variable = $variable;
    }
}

and I call it like this (without initializing it, or as far as php is concerned it's not even a class):

$my_class = null;
$v = $my_class->variable;

Is this allowed in php? It would give a big fat null pointer exception in most other languages. If it works, what's the value of variable?

Upvotes: 0

Views: 204

Answers (3)

Virk
Virk

Reputation: 21

class MyClass 
{
    public static $variable;

    public function __construct($variable) 
    {
        $this->variable = $variable;
    }
}

\MyClass::$variable = null;

echo \MyClass::$variable;

Upvotes: 0

xale94
xale94

Reputation: 424

That doesn't make sense...

If you declare a variable $my_class, and makes it NULL, every attribute given to that variable is null.

Of course, for php you're not doing anything wrong. You're just declaring that a variable is null.

This would be different if you declare $my_class as an object of your class MyClass, because you must give an attribute, even if this is null

Upvotes: 1

Finwe
Finwe

Reputation: 6735

It is "sort of" allowed - you will get a Notice: Trying to get property of non-object and the result will be NULL.

I anyway don't see a point of doing that.

Upvotes: 2

Related Questions