top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What’s the difference between accessing a class method via -> and via :: in php?

0 votes
503 views
What’s the difference between accessing a class method via -> and via :: in php?
posted Jun 25, 2014 by Karamjeet Singh

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

The -> is used for accessing properties and methods of instantiated objects.
:: is used for accesing static methods or attributes and don't require to instantiate an object of the class.
Example:
<?php
class Person
{
var $name = Mohit;

public function getName()
{
return $this->name;
}

public static function getAge()
{
return "24";
}
}
$person = new $person();
echo $person->getName();//Require to instantiate an object of the class.
echo person::getAge();//:: is used for accesing static methods(getAge), so don't require to instantiate an object of the class
?>
Output:
Mohit 24

answer Jun 26, 2014 by Mohit Sharma
Similar Questions
0 votes

Calling an overridden static method is easy, just go: parent::MethodName().

The point is that I want to have the same 'output' method name in both classes, so that whatever has one of them just calls $xxx->output() and it will work.

I want the method in the child class to use what the parent class has and just add a bit to it. I don't want to duplicate a lot of code in class B that is already in class A.

The way that I have a (hopefully temporary) workaround is to in class A have a method do_output() that is called by A::output() and B::output(). That works, but is clunky.

Is there a neat way of doing what I want ?

class A {
  private $v_a;

  // Does all sorts of things and returns a value
  function output() {
   return array('a' => $this->v_a);
  }
}

class B extends A {
  private $v_b;

  // Takes what output() in class A returns, adds some more and returns that
  function output() {
  $ret = parent::output();
   $ret['b'] = $this->v_b;
  return $ret;
  }
}

$var_a = new A;

$var_b = new B;

print_r($var_a->output());

// I want to see the value of v_a and v_b:
print_r($var_b->output());
0 votes

PHP:: Suppose I am trying to assign a variable the value of 0123, but it keeps coming up with a different number, whats the problem?

...