Which of the following is NOT a valid visibility keyword in PHP?

Understanding PHP Visibility Keywords

When working with object-oriented programming in PHP, three keywords describe the visibility of properties and methods: public, private, and protected. However, internal is not a valid keyword in PHP. Conversely, it's used in other languages like C# and represents a similar notion to protected in PHP.

PHP Visibility Keywords

Public

The public visibility keyword indicates that a property or method can be accessed anywhere - both inside and outside of the class. For example:

class MyClass {
  public $prop = "I'm a public property!";
}
$obj = new MyClass();
echo $obj->prop; // Prints "I'm a public property!"

Private

The private visibility keyword states that a property or method can only be accessed within the class that defines it. It means that if we attempt to access a private property or method from outside its class or from a child class, the PHP interpreter will return a fatal error. For example:

class MyClass {
  private $prop = "I'm a private property!";
}

$obj = new MyClass();
echo $obj->prop; // Fatal error: Uncaught Error: Cannot access private property

Protected

The protected visibility keyword means that a property or method can be accessed within the class it's defined or from its child classes. Unlike private, protected does not entirely restrict access outside its class, but atleast from classes that inherit from it. For instance:

class MyClass {
  protected $prop = "I'm a protected property!";
}

class ChildClass extends MyClass {
  public function printProp() {
    echo $this->prop; // Prints: I'm a protected property!
  }
}

$obj = new ChildClass();
$obj->printProp();

The Fallacy of internal

As the quiz question pointed out, internal is NOT a valid visibility keyword in PHP. Unlike public, private, or protected, internal does not exist in PHP. Attempting to use internal as a visibility keyword in PHP will result in a parsing error. However, developers familiar with languages such as C# or Java might assume it exists - where internal restricts access to the current assembly (for C#) or package (Java).

Best Practices

Choosing the right keyword for properties and methods can help ensure proper encapsulation in your PHP classes, which is a fundamental principle in Object-Oriented Programming. However, keep in mind that you should aim to keep as much of your object’s internal workings private as possible. Doing so can prevent unexpected modification from outside the class and enhance code maintainability.

In conclusion, understanding and using the right visibility keywords plays an inherent role in designing robust PHP classes, and as part of that, remember that internal is not a keyword in PHP.

Do you find this helpful?