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

I would like to know the difference between these two methods for initializing a class object

Method 1 (using the region resolution operator):

Test::foo();

Method 2 (creating an instance of the object):

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

and what is this operator ->called?

+3
source share
4 answers

Test::foo()just statically calls a class method, it does nothing with objects. It can initialize static values ​​in a class, but usually you do not use static initializers. A static initializer can be used internally in the case of Singletons , but you should never call an open static initializer like this.

$test = new Test , , , .

( //) ( ).

-> - T_OBJECT_OPERATOR.

+8
+2

lear oop (- ), PHP

, . *, foo 'static.

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
  • , .
+1

I call it an arrow ... but the difference is that using the arrow method you create a new instance of this class as an object, which can then be referenced as an object. The other simply calls a specific method of a particular class. Using an object, you can store the properties and functions of the call and store things in this object, and you can call several instances of this object and use them all separately ... I am incoherent, but there are many things that you can do with the object, which limited only by calling an individual method.

-1
source

All Articles