这两种初始化PHP类的方法有什么区别


What is the difference between this two methods for initializing a PHP class?

我想知道初始化类对象的这两种方法之间的区别

方法 1 (使用范围解析运算符) :

Test::foo();

方法 2(创建对象的实例):

$test = new Test;
$test->foo();

还有这个->运算符叫什么?

Test::foo()只是静态调用类的方法,它不对对象做任何事情。它可能会初始化类中的静态值,但通常不使用静态初始值设定项。对于单例,可以在内部使用静态初始值设定项,但切勿像这样调用公共静态初始值设定项。

$test = new Test实际上是实例化一个对象,在这个过程中它可能被初始化

请注意初始化(设置对象/类/变量的初始状态)和实例(从类创建对象实例)之间的区别。

->T_OBJECT_OPERATOR.

::被称为"Paamayim Nekudotayim"(希伯来语),->是对象运算符:

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

两者都不应用于初始化类。有一个神奇的__construct()方法,由new运算符自动调用:

http://php.net/manual/en/language.oop5.decon.php

Test::foo() 表示在实际对象范围之外静态foo()调用方法。可以将其视为某种(慢速)命名空间函数。

$test->foo() 表示对象$test的调用方法foo()

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

你需要 lear oop(面向对象编程),以及 PHP 上的这个实现

内部的函数称为方法,此方法可以在类的实例上调用,或者在静态模式下,第一次调用时,不要创建class*的实例,这称为方法"foo"静态。

class Test {
    public static $static_atribute;
    public $normal_atribute;
    public function Foo($q) {
         $this->normal_atribute = $q;
    }
    public static function SFoo ($q) {
         // I dont can access to $this
         self::$static_atribute = $q;
    }
}
Test::Foo("hello");
// This thrown an error because $this dont exist in static mode
Test::SFoo("hello");
//This works, and the static property change
echo Test::$static_atribute;
// this puts "hello"
echo Test::$normal_atribute;
// this thrown an error
$a = new Test();
// $a is an instance of Test
$a->foo("hello");
// this works and the normal_atribute change in THIS instance
$b = new Test();
// $b is anoter instance of Test
$b->foo("bye");
// normal_atribute change in THIS instance
echo $a->normal_atribute;
// puts hello
echo $b->normal_atribute;
// puts bye
  • 有一种模式,称为单例模式

我称之为箭头...但不同之处在于,使用 Arrow 方法,您将创建该类的新实例作为对象,然后可以将其作为对象引用。另一个只是调用某个类的某个方法。使用对象,您可以存储属性和调用函数并将内容存储在该对象中,并且可以调用该对象的多个实例并分别使用它们......我漫无边际,但你可以对一个对象做很多事情,这些事情仅限于调用单个方法。