Welcome back! Now that you've powered up your Spacecraft
class with attributes and methods, let's dive into the concept of visibility. This lesson is all about understanding how to control access to the data within your classes using getters
and setters
.
Visibility is essential for protecting and managing access to your class properties. Specifically, you'll learn how to use:
Getters
and Setters
to access and modify private attributes safely.In our Spacecraft
example, we'll see how to define both public and private properties and how to create getters
and setters
. This ensures that other parts of your program can interact with your class in a controlled and predictable way.
Here’s a sneak peek at what we’ll be working on:
php1<?php 2class Spacecraft { 3 // Public attribute that can be accessed from outside the class 4 public $publicName; 5 // Private attribute that can only be accessed within the class 6 private $privateName; 7 // Setter method for privateName 8 public function setPrivateName($name) { 9 $this->privateName = $name; 10 } 11 // Getter method for privateName 12 public function getPrivateName() { 13 return $this->privateName; 14 } 15} 16 17// Instantiate a new Spacecraft object 18$enterprise = new Spacecraft(); 19// Assign value to the public attribute 20$enterprise->publicName = "Enterprise"; 21// Use setter method to assign value to the private attribute 22$enterprise->setPrivateName("Secret Enterprise"); 23// Output the value of the public attribute 24echo $enterprise->publicName . "\n"; 25// Use getter method to access and output the value of the private attribute 26echo $enterprise->getPrivateName() . "\n"; 27?>
By mastering visibility, you'll be able to safeguard the internal state of your classes and prevent unauthorized modifications. This is crucial for writing robust and secure code.
For instance, imagine you have a financial application where you need to protect sensitive information. By using private properties and exposing them only through getters
and setters
, you can ensure that critical data is not accidentally or maliciously altered.
This skill is not just theoretical; it applies to real-world scenarios across different domains, such as software development, data security, and even game design. Understanding and using visibility controls effectively will vastly improve the reliability and maintainability of your code.
Ready to make your Spacecraft
class even more powerful and secure? Let's start the practice section to get hands-on experience with managing visibility using getters
and setters
!