开发者

Difference between :: and -> in PHP

I always see people in serious projects use :: everywhere, and -> only occasionally in local environment.

I only use -> myself and never end u开发者_Go百科p in situations when I need a static value outside of a class. Am I a bad person?

As I understand, the only situation when -> won't work is when I try following:

class StaticDemo {  
    private static $static  
}

$staticDemo = new StaticDemo( );

$staticDemo->static; // wrong  
$staticDemo::static; // right

But am I missing out on some programming correctness when I don't call simple public methods by :: ?

Or is it just so that I can call a method without creating an instance?


The double colon is used when you don't instantiate a class

class StaticDemo {...};
StaticDemo::static

if you do instantiate, use -->

class StaticDemo {...};
$s = new StaticDemo();
$s->static;

This is explained further at http://php.net/manual/en/language.oop5.patterns.php


:: is for referencing static properties or methods of a class. -> is for referencing instance properties and methods. You aren't missing out on any programming correctness, and if you are a bad person then it isn't because of this. Which one you use depends on the purpose of your class and how its written. But also, PHP didn't have namespaces until very recently so many people encapsulated their code in static classes to emulate namespaces to avoid naming collisions. It is possible you are seeing code that does that.


You caused a strict standards warning in E_STRICT mode. You are a bad person.

<?php

error_reporting(E_ALL | E_STRICT);

header('Content-type: text/plain');

class Foo {
    public $msg = "Hello, public.\n";
    public static $msgStatic = "Hello, static.\n";

    public function write() {
        echo "Hello, write.\n";
    }

    public static function writeStatic() {
        echo "Hello, writeStatic.\n";
    }
}

//echo Foo::$msg; // Fatal error: Access to undeclared static property: Foo::$msg
echo Foo::$msgStatic;
echo Foo::write(); // Strict Standards: Non-static method Foo::write() should not be called statically
echo Foo::writeStatic();

echo "------------------------\n";

$f = new Foo;
echo $f->msg;
echo $f->msgStatic; // Strict Standards: Accessing static property Foo::$msgStatic as non static
                    // Notice: Undefined property: Foo::$msgStatic
echo $f->write();
echo $f->writeStatic();

Output:

Hello, static.

Strict Standards: Non-static method Foo::write() should not be called statically in /home/adam/public_html/2010/05/10/bad.php on line 22
Hello, write.
Hello, writeStatic.
------------------------
Hello, public.

Strict Standards: Accessing static property Foo::$msgStatic as non static in /home/adam/public_html/2010/05/10/bad.php on line 29

Notice: Undefined property: Foo::$msgStatic in /home/adam/public_html/2010/05/10/bad.php on line 29
Hello, write.
Hello, writeStatic.


-> is for an instanciated class. :: is a static call.

:: is used in inheritance constructors (a child accessing a parent constructor) and when referring to a static method inside another method.

I wouldn't say not using static calls makes you a bad person either!


Yes, you can call a method or access a value without creating an instance.

It would be useful, for example, if you have a value that all instances of a class use. Say this value, however, needs to be initialized at the beginning of your app. You could use something like StaticDemo::static = 42; to initialize it, and then all instances of your class would be able to access it.


As I understand it the static is shared between objects of the same type:

class test{
    static function print_test(){
        print "hello!";
    }
}
$objectA = new test();
$objectB = new test();

The function print_test will be "shared" between the two objects. But the catch is the function print_test() should not reference anything inside the class! even thou PHP 5 accepts it.

Since the function print_test in the example just prints out "hello!" and doesn't reference anything inside the class why allocate memory for it in $objectA and $objectB? Just make one static function and $objectA and $objectB should point to it automatically.

Well that's the theory behind it in other languages, but since php5 allows you to reference $this in a static function I don't believe its a true static function since it would have to be dynamic to get any properties for ($this->variable) that unique object.


:: is used for static methods, which you call if you have no object instance.


Use "->" when in object context and "::" when accessing the class directly. In your example that would be:

class StaticDemo {
    public static $staticVar = 'blabla';
    public $normalVar = 'foobar';
}

$foo = new StaticDemo();
echo $foo->normalVar; //object context, echoes "foobar"
echo StaticDemo::staticVar; //class or "static" context, echoes "blabla"

Read this for detailed intel.


Or is it just so that I can call a method without creating an instance?

Correct.

The :: (scope resolution operators) are used when calling static methods/members. You don't have to create an instance to do this (like you did in your example).

Using -> and :: in the right context is the key to object-orientated programming correctness. You should only create static variables/methods when they apply to the class as a whole, and not only to a specific instance (object) of the class.


Static methods and properties are independent of a particular instantiation of a class. These must be accessed using double colons (::). Non-static methods and properties should be accessed using ->

This allows you do to some pretty cool things. A trivial example is a counter that keeps track of the number of instances of the class exists:

class foo {
  public static $i = 0;

  public function __construct() {
    self::$i++;
  }
}

$a = new foo();
$b = new foo();
echo foo::$i;
// outputs 2


As others have said,

  • :: 'double colon' is for referencing a static property or method.
  • -> 'dash arrow' is for referencing a property or method of a class instance.

But also its worth noting that

  • :: is often used in texts as shorthand to refer to a property or method that belongs to a certain class (whether it's static or instance).

See the 'Note...in documentation...' : http://books.google.co.uk/books?id=qVLjFk_4zVYC&lpg=PA66&dq=php%205%20objects&pg=PA46#v=onepage&q=php%205%20objects&f=false


Well you're right about how to use -> and ::. But sometimes it just doesn't make much sense to create objects of a class. Here's an example Compare

class Settings
{
    public static $setting1;
    public static $setting2;
    ... // lots of other vars and functions
}
if(Setting::$setting1)
    //do something

vs

class Settings
{
    public $setting1;
    public $setting2;
    ... // lots of other vars and functions
}
$set = new Settings()
if($set->setting1)
    //do something

As I said It doesn't make sense to create instances as there's always only required one. in this case static fits better. It turns out in web we mostly deal with this kind of case unless you're dealing with real Objects e.g. users etc hence the prevalence of the former

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜