DEV Community

Egor
Egor

Posted on

How to access private properties of a class outside the context of the class itself (PHP)

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);
Enter fullscreen mode Exit fullscreen mode

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)