Question

http://codepad.viper-7.com/ezvlkQ

So, I'm trying to figure out:


...?php

$object = new A();

class A 
{
  static public $foo = 'bar';
  function displayFoo()
  {
    echo $this->$foo;
  }
}

A::displayFoo();
A->displayFoo();
?>

About this, how many errors can you find? Can you tell me what they are in real human terms? I can't really interpret what is and what is not okay from the validator that codepad uses...

Was it helpful?

Solution

I’ve updated your code here http://codepad.viper-7.com/UaUE4g

Error 1:

echo $this->$foo;

This should read:

echo self::$foo;

.. as it is static.

Error 2:

A::displayFoo();

The method is an instance method :: is used for access to static methods.

Error 3:

A->displayFoo();

This is an error because A is undefined and if it was it should have read $A. This would be okay:

$object->displayFoo();

.. as $object is an instance of class A.

Next step, consult the manual on the topic static.

OTHER TIPS

Not sure where to start. Static methods belong to the class, normal methods belong to an object, an instantiation of that class. For example, you can have:

Class A {
   static public $foo = 'WOOHOOO';
   static function displayFoo() {
       echo self::$foo;
   }
}

echo A::displayFoo();

This works because you're calling the displayFoo method belonging to class A. Or you can do this:

Class A {
    public $foo = "WOOHOO";
    public function displayFoo() {
        echo $this->foo;
    }
}

$obj = new A();
$obj->displayFoo();

Now you're creating an object based on the class of A. That object can call its methods. But the object doesn't have static methods. If you were to declare the function static, it would not be available to $obj.

You can't do:

A->displayFoo()

at all, under any circumstances, ever. The -> operator assumes an object, and A can't be an object because its not a variable.

You can read up on static class members in the manual here:

http://php.net/static

Pay close attention to the examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top