PHP: Difference between -> and :: [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In PHP, whats the difference between :: and ->?
In PHP, what is the main difference of while calling a function() inside a class with arrow -> and Scope Resolution Operator :: ?
For more clearance, the difference between:
$name = $foo->getName();
$name = $foo::getName();
What is the main profit of Scope Resolution Operator :: ?

$name = $foo->getName();
This will invoke a member or static function of the object $foo, while
$name = $foo::getName();
will invoke a static function of the class of $foo. The 'profit', if you wanna call it that, of using :: is being able to access static members of a class without the need for an object instance of such class. That is,
$name = ClassOfFoo::getName();

-> is called to access a method of an instance (or a variable of an instanciated object)
:: is used to access static functions of an uninstanced object

They are for different function types. -> is always used on an object for static and non-static methods (though I don't think it's good practice use -> for static methods). :: is only used for static methods and can be used on objects (as of PHP 5.3) and more importantly classes.
<?php
class aClass {
static function aStaticMethod() {}
function aNormalMethod() {}
}
$obj = new aClass();
$obj->aNormalMethod(); //allowed
$obj->aStaticMethod(); //allowed
$obj::aStaticMethod(); //allowed as of PHP 5.3
$class_name = get_class( $obj );
$class_name::aStaticMethod(); //long hand for $obj::aStaticMethod()
aClass::aStaticMethod(); //allowed
//aClass::aNormalMethod(); //not allowed
//aClass->aStaticMethod(); //not allowed
//aClass->aNormalMethod(); //not allowed

Related

Calling static functions with $this [duplicate]

This question already has answers here:
PHPUnit - Use $this or self for static methods?
(3 answers)
When should I use 'self' over '$this'?
(23 answers)
Closed 3 years ago.
I was messing around and discovered that you could actually call static methods with $this->method()
And it got me a bit confused and curious about the differences between the 3 ways (that I know of) to call static methods
$this->method();
static::method();
self::method();
Now, I think I understand the difference between the latter two, but what about the first one?
It is important to understand the behavior of static properties in the context of class inheritance:
Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.
Static properties defined ONLY in the parent class will share a COMMON value.
declare(strict_types=1);
class staticparent {
static $parent_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromparent';
static::$both_distinct = 'fromparent';
}
}
class staticchild extends staticparent {
static $child_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromchild';
static::$both_distinct = 'fromchild';
static::$child_only = 'fromchild';
}
}
$a = new staticparent;
$a = new staticchild;
More on https://www.php.net/manual/en/language.oop5.static.php
self using for static method and variable in class
$this using for non static method and variable
static generally using call child class of static methods or variable
For example late static
For example late static binding

Diffrences of $this:: and $this-> in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: self vs. $this
I've found that I can call class methods by $this:: prefix. example:
class class1 {
public function foo()
{
echo "1";
}
public function bar()
{
$this::foo();
//in this example it acts like $this->foo() and displays "2"
//using self::foo() displays "1"
}
}
class class2 {
public function foo()
{
echo "2";
}
public function bar()
{
class1::bar();
}
}
$obj = new class2();
$obj->bar(); // displays "2"
class1::bar(); // Fatal error
I want to know whats the diffrence of calling method with $this-> and $this:: prefixes.
ps:
There is a page about diffrence of $this->foo() and self::foo() in this link:
When to use self over $this?
The answer that you linked tells you exactly what you're looking for ;).
Basically, there are two concepts that some people have a tough time differentiating in programming languages: objects and classes.
A class is abstract. It defines a structure of an object. The properties and methods that an object would contain, if an object were built from that class. Creating an object is what you do when you call new class1(). This is instructing PHP to create a new object with all of the properties and methods on the class1 class.
The important thing to note about creating an object is that it also has its own scope. This is really where $this vs static:: (note: do not use self:: or $this::, please use static:: (more on this later)) come in to play. Using $this is instructing PHP to access the properties and methods of your current object. Using static:: is instructing PHP to access the properties and methods of the base class that your object is constructed from.
Here's an example:
class MyClass {
public $greeting;
public static $name;
public greet() {
print $this->greeting . " " . static::$name;
}
}
$instance1 = new MyClass();
$instance1->greeting = 'hello';
$instance2 = new MyClass();
$instance2->greeting = 'hi';
MyClass::$name = 'Mahoor13';
$instance1->greet();
$instance2->greet();
I didn't test the above, but you should get:
hello Mahoor13
hi Mahoor13
That should give to a general idea of the difference between setting a class property and setting an instance property. Let me know if you need additional help.
Edit
$this:: appears to just be a side effect of the way that PHP handles scopes. I would not consider it valid, and I wouldn't use it. It doesn't appear to be supported in any way.
the $this-> is called from instance , so you have to have an instance of the object to use this call.
but $this:: is a static method inside the class you can call it without instance so you do not need to alloc an instance of the class to call it like
myclass::doFoo();
public static function doFoo(){ .... }
and the do function should be static function to call it like this or the php will give error in the newer versions

what is the "::" notation in php used for?

I am looking through some php code and I see this "::" notation that i have no idea what it means...also what the & in the front of the call
$mainframe =& JFactory::getApplication('site');
$sql="SELECT rt.member_id ,rt.commission,rt.sales,kt.store_id,kt.user_id FROM jos_report
rt JOIN jos_kingdom_tickets kt WHERE rt.member_id=kt.ticket_id";
$db =& JFactory::getDBO();
thanks in advance
::, the scope resolution operator, is used for referencing static members and constants of a class. It is also used to reference a superclass's constructor. Here is some code illustrating several different uses of the scope resolution operator:
<?php
class A {
const BAR = 1;
public static $foo = 2;
private $silly;
public function __construct() {
$this->silly = self::BAR;
}
}
class B extends A {
public function __construct() {
parent::__construct();
}
public static function getStuff() {
return 'this is tiring stuff.';
}
}
echo A::BAR;
echo A::$foo;
echo B::getStuff();
?>
A little trivia: The scope resolution operator is also called "paamayim nekudotayim", which means "two dots twice" in hebrew.
& in the context of your example isn't doing anything useful if you are using php 5 or greater and should be removed. In php 4, this used to be necessary in order to make sure a copy of the returned object wasn't being used. In php 5 object copies are not created unless clone is called. And so & is not needed. There is still one case where & is still useful in php 5: When you are iterating over the elements of an array and modifying the values, you must use the & operator to affect the elements of the array.
You can use it to reference static methods from a class without having to instantiate it.
For example:
class myClass {
public static function staticFunction(){
//...
}
public function otherFunction(){
//...
}
}
Here you could use myClass::staticFunction() outside of the class, but you would have to create a new myClass object before using otherFunction() in the same way.
:: is the scope operator in PHP, c++, but not in Java. In this case, it is used to call a static method of a class. A static method is a method which can be called from outside the class, even when you don't have an instance of it.
& indicates that rather than making a copy of what the function returns, it takes the reference to the object returned. In this case, they seem to return singleton objects which are used in the application, e.g. to interface with the database (in the second case)
It's the scope operator, used for referencing constants or static methods under classes. So:
class C {
const D = 2;
}
echo C::D; // 2
In your case, it calls a method of the class not tied to a particular instance.

difference between :: and -> in calling class's function in php

I have seen function called from php classes with :: or ->.
eg:
$classinstance::function
or
$classinstance->function
whats the difference?
:: is used for scope resolution, accessing (typically) static methods, variables, or constants, whereas -> is used for invoking object methods or accessing object properties on a particular object instance.
In other words, the typical syntax is...
ClassName::MemberName
versus...
$Instance->MemberName
In the rare cases where you see $variable::MemberName, what's actually going on there is that the contents of $variable are treated as a class name, so $var='Foo'; $var::Bar is equivalent to Foo::Bar.
http://www.php.net/manual/en/language.oop5.basic.php
http://www.php.net/manual/language.oop5.paamayim-nekudotayim.php
The :: syntax means that you are calling a static method. Whereas the -> is non-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();
Example:
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*
::function is for static functions, and should actually be used as:
class::function() rather than $instance::function() as you suggest.
You can also use
class::function()
in a subclass to refer to parent's methods.
:: is normally used for calling static methods or Class Constants. (in other words, you don't need to instantiate the object with new) in order to use the method. And -> is when you've already instantiated a object.
For example:
Validation::CompareValues($val1, $val2);
$validation = new Validation;
$validation->CompareValues($val1, $val2);
As a note, any method you try to use as static (or with ::) must have the static keyword used when defining it. Read the various PHP.net documentation pages I've linked to in this post.
With :: you can access constants, attributes or methods of a class; the variables and methods need to be declared as static, otherwise they do belong to an instance and not to the class.
And with -> you can access attributes or methods of an instance of a class.

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 up 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

Categories