How to access private properties of a class outside the context of the class itself (PHP)
Egor
Posted on October 16, 2023
One way to access the private properties of a class outside of its context is closure.
Example:
<?php
class Worker {
public function __construct(
public readonly string $name,
private readonly float $hourlyRate
) {
}
public function calculateSalary(float $hours): float|int
{
return $this->hourlyRate * $hours;
}
}
$bob = new Worker('Bob', 3.5);
$bobHourlyRate = (function(): float {
return $this->hourlyRate;
})->call($bob);
But I want to warn you right away, it's worth being extremely careful to use accesses to private class properties in one way or another, since these properties probably have this scope for a reason and the author of the code would not want these properties to be used outside.
đź’– đź’Ş đź™… đźš©
Egor
Posted on October 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.