Information Hiding
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 41 of 91.
Information hiding is the principle behind encapsulation - the idea that a class should expose only what's necessary and hide its internal implementation details. While access modifiers and getters/setters are the tools, information hiding is the design philosophy that guides how you use them.
The goal is to create a clear boundary between what a class does (its public interface) and how it does it (its internal implementation). This separation means you can change the internal workings without affecting code that uses the class:
<?php
class Temperature {
private float $celsius;
public function setCelsius(float $value): void {
$this->celsius = $value;
}
public function getCelsius(): float {
return $this->celsius;
}
public function getFahrenheit(): float {
return ($this->celsius * 9/5) + 32;
}
}
$temp = new Temperature();
$temp->setCelsius(25);
echo $temp->getCelsius() . "C = " . $temp->getFahrenheit() . "F";
Output:
25C = 77FThe class stores temperature internally in Celsius, but users don't need to know this. You could later change the internal storage to Fahrenheit or Kelvin, and as long as the public methods still work the same way, no external code breaks.
Key Point: Information hiding protects your code from changes. Hide implementation details, expose only stable interfaces, and your classes become easier to maintain and modify over time.
Challenge
EasyLet's build a currency converter that demonstrates information hiding in action. You'll create a class that stores money internally in one currency but can seamlessly convert to and from multiple currencies — without external code ever knowing how the data is actually stored.
You'll organize your code across two files:
Money.php— Create aMoneyclass that internally stores all amounts in cents (as an integer) to avoid floating-point precision issues. This implementation detail should be completely hidden from users of the class. The class should provide:- A private property to store the amount in cents
setDollars(float $amount)— accepts a dollar amount and stores it internally as centsgetDollars()— returns the amount as dollars (float, 2 decimal places)setEuros(float $amount)— accepts euros and converts to cents using the rate: 1 EUR = 1.10 USDgetEuros()— returns the amount converted to euros (float, 2 decimal places)getInternalValue()— returns the raw cents value (integer) for debugging purposes
main.php— Include the Money file. You'll receive two inputs: a dollar amount and a euro amount. Create aMoneyinstance. First, set the dollar amount (converted to float) and print three lines: the dollars value, the euros equivalent, and the internal cents value. Then set the euro amount (converted to float) and print the same three values again.
The beauty of this design is that external code works with familiar dollar and euro values, completely unaware that everything is stored as cents internally. You could later change the internal storage to use a different base currency or a different precision strategy, and as long as the public methods continue to work correctly, no external code would need to change.
Format all dollar and euro outputs to exactly 2 decimal places. Each value should be printed on its own line, resulting in six lines of output total.
Cheat sheet
Information hiding is the principle behind encapsulation - exposing only what's necessary while hiding internal implementation details. This creates a clear boundary between what a class does (public interface) and how it does it (internal implementation).
Example of information hiding with a Temperature class:
<?php
class Temperature {
private float $celsius;
public function setCelsius(float $value): void {
$this->celsius = $value;
}
public function getCelsius(): float {
return $this->celsius;
}
public function getFahrenheit(): float {
return ($this->celsius * 9/5) + 32;
}
}
$temp = new Temperature();
$temp->setCelsius(25);
echo $temp->getCelsius() . "C = " . $temp->getFahrenheit() . "F";
// Output: 25C = 77F
The class stores temperature internally in Celsius, but users don't need to know this. The internal storage could be changed to Fahrenheit or Kelvin without breaking external code, as long as the public methods continue to work the same way.
Key benefits: Information hiding protects code from changes. By hiding implementation details and exposing only stable interfaces, classes become easier to maintain and modify over time.
Try it yourself
<?php
require_once 'Money.php';
// Read inputs
$dollarAmount = floatval(trim(fgets(STDIN)));
$euroAmount = floatval(trim(fgets(STDIN)));
// TODO: Create a Money instance
// TODO: Set the dollar amount and print:
// - The dollars value (2 decimal places)
// - The euros equivalent (2 decimal places)
// - The internal cents value (integer)
// TODO: Set the euro amount and print:
// - The dollars value (2 decimal places)
// - The euros equivalent (2 decimal places)
// - The internal cents value (integer)
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern