Bird
Raised Fist0
PHPprogramming~10 mins

Properties and visibility in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Properties and visibility
Define Class with Properties
↓
Set Property Visibility: public/private/protected
↓
Create Object Instance
↓
Access Properties
This flow shows how properties are defined with visibility and how they can be accessed depending on their visibility.
Execution Sample
PHP
<?php
class Car {
  public $color = 'red';
  private $speed = 0;
}
$car = new Car();
echo $car->color;
echo $car->speed; // error
?>
Defines a class with public and private properties, then accesses the public property successfully and shows private property access causes error.
Execution Table
StepActionProperty AccessResultNotes
1Create object $carN/AObject createdProperties initialized: color='red', speed=0
2Access $car->colorpublicOutputs 'red'Public property accessible from outside
3Access $car->speedprivateError: Cannot access private propertyPrivate property not accessible outside class
4EndN/AExecution stops due to errorPrivate property access blocked
💡 Execution stops at step 3 because private property access from outside the class is not allowed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
$car->colorundefined'red''red''red'
$car->speedundefined000
Key Moments - 2 Insights
Why does accessing $car->speed cause an error?
Because $speed is declared private, it cannot be accessed from outside the class. See execution_table step 3.
Can we access $car->color from outside the class?
Yes, because $color is declared public, it is accessible from outside. See execution_table step 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when accessing $car->color at step 2?
A'red'
BError
Cnull
DUndefined property
💡 Hint
Check execution_table row with Step 2 for the output of $car->color access.
At which step does the program stop due to an error?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
See execution_table exit_note and step 3 where private property access causes error.
If $speed was declared public instead of private, what would happen at step 3?
AOutput 'red'
BError
COutput '0'
DNo change
💡 Hint
Refer to variable_tracker and execution_table step 3 about property visibility effects.
Concept Snapshot
Properties in PHP classes have visibility: public, private, or protected.
Public properties can be accessed anywhere.
Private properties can only be accessed inside the class.
Protected properties can be accessed inside the class and subclasses.
Trying to access private or protected properties from outside causes errors.
Full Transcript
This example shows a PHP class Car with two properties: color (public) and speed (private). When we create an object of Car, the properties are initialized. Accessing the public property color from outside the class works and outputs 'red'. However, trying to access the private property speed from outside causes an error and stops execution. This demonstrates how property visibility controls access in PHP classes.

Practice

(1/5)
1. Which visibility keyword allows a property to be accessed from anywhere, including outside the class?
easy
A. private
B. public
C. protected
D. static

Solution

  1. Step 1: Understand visibility keywords

    Public properties can be accessed from anywhere, protected only within the class and subclasses, private only inside the class.
  2. Step 2: Identify which keyword allows outside access

    Only public allows access from outside the class.
  3. Final Answer:

    public -> Option B
  4. Quick Check:

    public = accessible everywhere [OK]
Hint: Public means accessible everywhere, no restrictions [OK]
Common Mistakes:
  • Confusing protected with public
  • Thinking private allows outside access
  • Mixing static with visibility
2. Which of the following is the correct way to declare a private property named $name in a PHP class?
easy
A. private $name;
B. var $name;
C. public $name;
D. protected $name;

Solution

  1. Step 1: Recall PHP property declaration syntax

    Properties are declared with visibility keyword followed by variable name and semicolon.
  2. Step 2: Identify private property syntax

    Correct syntax is private $name;. The var keyword is outdated and defaults to public.
  3. Final Answer:

    private $name; -> Option A
  4. Quick Check:

    private property declaration uses 'private' keyword [OK]
Hint: Use 'private' keyword before $property for private visibility [OK]
Common Mistakes:
  • Using 'var' instead of visibility keywords
  • Omitting the $ sign
  • Using public or protected instead of private
3. What will be the output of this PHP code?
class Car {
  private $color = 'red';
  public function getColor() {
    return $this->color;
  }
}
$car = new Car();
echo $car->getColor();
medium
A. Empty string
B. Error: Cannot access private property
C. null
D. red

Solution

  1. Step 1: Understand private property access

    The property $color is private, so it cannot be accessed directly outside the class.
  2. Step 2: Check method usage to access private property

    The public method getColor() returns the private property value, so calling it outputs 'red'.
  3. Final Answer:

    red -> Option D
  4. Quick Check:

    Private property accessed via public method = 'red' [OK]
Hint: Use public methods to access private properties safely [OK]
Common Mistakes:
  • Trying to access private property directly
  • Expecting an error when using a getter method
  • Confusing null with private property value
4. Identify the error in this PHP class code:
class Person {
  protected $age;
  public function setAge($age) {
    $this->age = $age;
  }
}
$person = new Person();
echo $person->age;
medium
A. Method setAge should be private
B. Missing semicolon after property declaration
C. Cannot access protected property directly outside class
D. Class name should be lowercase

Solution

  1. Step 1: Understand protected property visibility

    Protected properties cannot be accessed directly from outside the class or its subclasses.
  2. Step 2: Analyze code usage of protected property

    The code tries to echo $person->age directly, which causes an error due to protected visibility.
  3. Final Answer:

    Cannot access protected property directly outside class -> Option C
  4. Quick Check:

    Protected = no direct outside access [OK]
Hint: Protected properties need methods for outside access [OK]
Common Mistakes:
  • Trying to access protected property directly
  • Confusing protected with public
  • Ignoring visibility rules
5. Given this PHP class, what is the best way to safely update the private property $score only if the new score is higher?
class Game {
  private $score = 0;
  public function updateScore(int $newScore) {
    // What code should go here?
  }
  public function getScore() {
    return $this->score;
  }
}
hard
A. if ($newScore > $this->score) { $this->score = $newScore; }
B. $this->score = $newScore;
C. return $newScore > $this->score;
D. if ($newScore < $this->score) { $this->score = $newScore; }

Solution

  1. Step 1: Understand the requirement to update only if new score is higher

    The property $score should change only when $newScore is greater than current $score.
  2. Step 2: Choose the correct conditional update code

    if ($newScore > $this->score) { $this->score = $newScore; } checks if $newScore is greater, then updates $score. Other options either overwrite unconditionally or do wrong comparison.
  3. Final Answer:

    if ($newScore > $this->score) { $this->score = $newScore; } -> Option A
  4. Quick Check:

    Update only if newScore > current score [OK]
Hint: Use if condition to update private property safely [OK]
Common Mistakes:
  • Updating score without condition
  • Using wrong comparison operator
  • Returning boolean instead of updating property
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard