我想知道初始化类对象的这两种方法之间的区别。
方法1(使用作用域解析运算符):
方法二(创建对象实例):
还有,这个
方法1(使用作用域解析运算符):
Test::foo();
方法二(创建对象实例):
$test = new Test;
$test->foo();
还有,这个
->
操作符叫什么名字?Test::foo()
仅仅是静态调用一个类的方法,它不会对对象进行任何操作。它可能会在类中初始化静态值,但你通常不会使用静态初始化器。静态初始化器可能在单例模式的情况下在内部使用,但你不应该像这样调用公共静态初始化器。
$test = new Test
实际上是实例化一个对象,在此过程中它很可能被初始化。->
是T_OBJECT_OPERATOR
。::
被称为“Paamayim Nekudotayim”(希伯来语),->
是对象操作符:
http://www.php.net/manual/zh/language.oop5.paamayim-nekudotayim.php
都不应被用于初始化类。有一个神奇的__construct()
方法专门用于这个目的,它会被new
操作符自动调用:
http://php.net/manual/zh/language.oop5.decon.php
Test::foo()
意味着静态调用方法 foo()
,并超出实际对象的范围。可以将其视为某种(较慢的)命名空间函数。
$test->foo()
意味着为对象$test调用方法 foo()
。
你需要学习面向对象编程(面向对象编程),以及在PHP中的实现。
类内部的函数称为方法,这些方法可以在类的实例或静态模式下调用。第一次调用不会创建类的实例* ,这种情况下称为静态方法 '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
我称它为箭头...但不同之处在于,使用箭头方法时,您正在创建该类的新实例作为对象,然后可以将其引用为对象。另一个方法仅调用某个类的特定方法。使用对象,您可以存储属性和调用函数并在该对象中存储内容,并且您可以调用该对象的多个实例并单独使用它们...我在胡言乱语,但是使用对象可以做很多事情,而仅调用单个方法则有限制。