1

I have a class that look like this

class a {

    private $one;

    private function abc() {

    $this->one = "I am a string";
    return $this;
}

$call = new a;
$call->abc()->other_function();

As I was doing matutor method, php has caught a fatal error on calling function abc(). It said Call to private method xxx from context.

What I know of oop is very new, that private method/property can only be used within the same class.However, I cannot call the abc() even it is within the same class.

How come?

3
  • 4
    You can call it from within the class. Not outside of it. To call it outside of the class it must be public. Commented Mar 12, 2015 at 13:56
  • Thanks for the insight. Dont know why I get -1 for being a bit ignorant....I tried to look for an answer, but cant find it stated clearly on this..... @AndreiP. if I have multiple property to return, how will I do this? Thanks :) Commented Mar 12, 2015 at 14:02
  • Encapsulate the properties to return into an array, and return that array, but this is already another question. Commented Mar 12, 2015 at 14:07

2 Answers 2

0

Because you are not calling the method inside the class you are doing so outside the class code.

$call = new a;
$call->abc()->other_function();

this is outside the context of the class, and this is why you get a Fatal Error.

Sign up to request clarification or add additional context in comments.

Comments

0

Private can only be used in the class itself.

Protected can only be used in the class itself and child classes.

Public can be used anywhere.

class a {

    private $one;

    public function abc() { //notice the public

      $this->one = "I am a string";
      return $this->one; 
    }
}

$call = new a;
echo $call->abc();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.