访问方法 - >和访问方法有什么区别::

What is the basic difference between calling a method using -> and ::

 class a 
  {
    function b()
     {
         echo "abc"; 
     }
  }

What is the difference between these two?

  1. a::b();
  2. $c = new a; $c->b();

-> executes the method in the context of an instance, while :: accesses the method in static context of a class. The latter only has access to static members of the class via self::, while the former can also use the instance members via $this->.

    a::b();

The above statement used to call static method in the context of class(independent of any object cotext) thus $this is not available in static method

    $c = new a; $c->b();

The above satement used to call instance method in the context of object($c) thus $this(refer to object $c) is available inside instance method

Thanks

When defining your class, you should be explicitly declare the visibility of your properties and methods, and whether or not they are static.

The class in your example should be:

class A 
{
    public static function b() {
        echo "abc"; 
    }
}

The method b() should be static because it doesn't refer to any instance variables. To call b() you would use:

A::b();

If your method was to use an instance variable (a non-static property) your class would probably look like this:

class Foo
{
    private $bar;   // non static instance variable

    public function __construct($bar) {
        $this->bar = $bar;  // instance variable set in the constructor
    }

    public function baz() {
        echo $this->bar;  // instance variable referred to in the non-static method
    }
}

Then you would call the function like this:

$x = new Foo('abc');
$x->baz();