• 6
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 187

Backtrace:

File: /home/prodcxja/public_html/questions/application/views/question.php
Line: 187
Function: _error_handler

File: /home/prodcxja/public_html/questions/application/controllers/Questions.php
Line: 433
Function: view

File: /home/prodcxja/public_html/questions/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

PHP classes why use public keyword?

Why should I declare class properties (variables) or methods (functions) using the keyword public, if they're public by default? Or, are they?

To phrase my question differently, is public redundant? I understand private and protected, but why declare public if class members are public anyway?

Yes, public is the default (see visibility docs).

People add it, so it is consistent with all the other methods / properties.

Furthermore, if you want to declare a property public and don't want to use public you will need to use var, which is not recommended and will likely be deprecated at some point.

  • 8
Reply Report
      • 1
    • For properties, ok. But who really needs public properties nowadays? For public methods, it is a matter of convention (e.g. PSR-2), which is good for familiarity and interoperability. But there is no technical benefit. And, I would argue, it does not improve readability, if your brain is not already used to seeing the public keyword.

As of php 5.3 (I think, its been a while), using the var keyword raises E_STRICT errors, so public has to be used to declare object vaiables. As for functions, I believe it is more of a consistency thing.

  • 3
Reply Report

Sure it is redundant since that is the default visibility level. You should avoid them when you can. Some people add the public keyword explicitly so that code is little more readable.

  • 2
Reply Report