Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JayDee84's avatar

PHP-PRIVATE-or-PUBLIC METHOD(FUNCTION)

Hello everybody, i am here with one doubt in my mind,

if we have a class in php with protected or private properties , we can access them with help of a public method, how is it possibile to access a private or protected method??? *

0 likes
5 replies
manelgavalda's avatar

You already said how to access private or protected methods outside the class, using public methods as a wrappers(getter, setter):

  • You can only access private methods in your own class.
  • You can access protected methods in the own class and the childs from the class.
1 like
primordial's avatar

Public scope to make that variable/function available from anywhere, other classes and instances of the object.

Private scope when you want your variable/function to be visible in its own class only.

Protected scope when you want to make your variable/function visible in all classes that extend current class including the parent class.

https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected

1 like
JayDee84's avatar

@GLOBALS - can u please explain how to call a private method within class ? As we can access the properties by another public method as u wrote, but how if we have a private method? for ex:

class Person{ private $name; private $age;

private function __construct($name, $age){

}

}

P.S: I am not thinking about a child class. Even not sure if i wrote the example in right manner. Hope u understand what i mean to say. Thanks

Sergiu17's avatar

how is it possibile to access a private or protected method

With a public method, lol

2 likes

Please or to participate in this conversation.