代码之家  ›  专栏  ›  技术社区  ›  Jonathan.

PHP中调用类函数时::和->的区别

  •  0
  • Jonathan.  · 技术社区  · 14 年前

    我见过用::或->从PHP类调用的函数。

    如:

    $ClassInstance::函数 或 $ClassInstance->函数

    有什么区别?

    6 回复  |  直到 14 年前
        1
  •  1
  •   Greg W    14 年前

    这个 :: 语法意味着您正在调用 static 方法。鉴于 -> 是非静态的。

    MyClass{
    
      public function myFun(){  
      }
    
      public static function myStaticFun(){
      }
    
    }
    
    $obj = new MyClass();
    
    // Notice how the two methods must be called using different syntax
    $obj->myFun();
    MyClass::myStaticFun();
    
        2
  •  2
  •   Amber    14 年前

    :: 用于 scope resolution ,访问(通常) 静止的 方法、变量或常量,而 -> 用于 invoking object methods or accessing object properties 在特定对象实例上。

    换句话说,典型的语法是…

    ClassName::MemberName
    

    对…

    $Instance->MemberName
    

    在罕见的情况下 $variable::MemberName ,实际情况是 $variable 被治疗 作为类名 如此 $var='Foo'; $var::Bar 等于 Foo::Bar .

    http://www.php.net/manual/en/language.oop5.basic.php

    http://www.php.net/manual/language.oop5.paamayim-nekudotayim.php

        3
  •  1
  •   NikiC    14 年前

    例子:

    class FooBar {
        public function sayHi() { echo 'Hi!'; }
        public /* --> */ static /* <-- */ function sayHallo() { echo 'Hallo!'; }
    }
    
    // object call (needs an instance, $foobar here)
    $foobar = new FooBar;
    $foobar->sayHi();
    
    // static class call, no instance required
    FooBar::sayHallo(); // notice I use the plain classname here, not $foobar!
    
    // As of PHP 5.3 you can write:
    $nameOfClass = 'FooBar'; // now I store the classname in a variable
    $nameOfClass::sayHallo(); // and call it statically
    
    $foobar::sayHallo(); // This will not work, because $foobar is an class *instance*, not a class *name*
    
        4
  •  0
  •   m1tk4    14 年前

    ::函数用于静态函数,实际应用为:

    class::function()而不是您建议的$instance::function()。

    您也可以使用

    类::函数()

    在子类中引用父类的方法。

        5
  •  0
  •   Dominic Barnes    14 年前

    :: 通常用于呼叫 static 方法或 Class Constants . (换句话说,您不需要用 new )为了使用这个方法。和 -> 当您已经实例化了一个对象时。

    例如:

    Validation::CompareValues($val1, $val2);
    
    $validation = new Validation;
    $validation->CompareValues($val1, $val2);
    

    请注意,您尝试用作静态(或 :: )在定义静态关键字时必须使用该关键字。阅读我在本文中链接到的各种php.net文档页面。

        6
  •  0
  •   Gumbo    14 年前

    :: 您可以访问 ;变量和方法需要声明为静态的,否则它们属于一个实例而不是类。

    -> 您可以访问 类的实例 .