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.
Top comments (0)