Asked  7 Months ago    Answers:  3   Viewed   26 times

I am confused with & and &&. I have two PHP books. One says that they are same, but the another says they are different. I thought they are same as well.

Aren't they same?

 Answers

82

& is bitwise AND. See Bitwise Operators. Assuming you do 14 & 7:

    14 = 1110
     7 = 0111
    ---------
14 & 7 = 0110 = 6

&& is logical AND. See Logical Operators. Consider this truth table:

 $a     $b     $a && $b
false  false    false
false  true     false
true   false    false
true   true     true
Wednesday, March 31, 2021
 
JakeGR
answered 7 Months ago
37

-> is used when referring to a member of an object.

:: is the Scope Resolution Operator and is used to refer to a static member of a Class.

Consider the following class:

class FooBar {
    public static function fizz() {
        echo "Fizz";
    }

    public function buzz() {
        echo "Buzz";
    }
}

You would call the function buzz() using ->:

$myFooBar = new FooBar();
$myFooBar->buzz();

But would use :: to call the functon fizz(), as it is a static member (a member which doesn't require an instance of the class to be called):

FooBar::fizz();

Also, while we are talking about the difference between static members versus instantiated members, you cannot use $this to refer to the current instance within static members. You use self instead (no leading $) which refers to the current class, or parent if you want to refer to the parent class, or if you have the pleasure of working with PHP 5.3.0, static (which allows for late static binding).


The documentation uses :: to refer to a function inside a class as the class name in the header is not an instance of the class. Still using the same example, a documentation entry referring to the function buzz() would use the following header:

FooBar::buzz

But unless the documentation specifies it's a static member, you will need to use -> on an instance to call it:

$myFooBar = new FooBar();
$myFooBar->buzz();
Wednesday, March 31, 2021
 
Sufi
answered 7 Months ago
27

:: 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.

Wednesday, March 31, 2021
 
diegoiglesias
answered 7 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :