PHP equivalent of friend or internal

PHP doesn't natively support friend classes like C++, but it can be simulated using magic methods __get() and __set() along with debug_backtrace(). This approach allows specific classes to access private properties, though it's considered a workaround rather than best practice.

Simulating Friend Classes

Here's how to implement friend-like behavior by checking the calling class in the backtrace ?

<?php
class SampleFriend {
    private $__friends = array('My_Friend', 'Other_Friend');
    private $secret_data = "This is private data";
    
    public function __get($key) {
        $trace = debug_backtrace();
        if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) {
            return $this->$key;
        }
        trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
    }
    
    public function __set($key, $value) {
        $trace = debug_backtrace();
        if(isset($trace[1]['class']) && in_array($trace[1]['class'], $this->__friends)) {
            return $this->$key = $value;
        }
        trigger_error('Cannot access private property ' . __CLASS__ . '::$' . $key, E_USER_ERROR);
    }
}

class My_Friend {
    public function accessFriend($obj) {
        return $obj->secret_data; // This will work
    }
}

class Stranger {
    public function accessFriend($obj) {
        return $obj->secret_data; // This will trigger error
    }
}

// Testing the friend access
$sample = new SampleFriend();
$friend = new My_Friend();

echo $friend->accessFriend($sample);
?>
This is private data

Alternative Approach: Protected Properties

A cleaner approach is using protected properties with inheritance ?

<?php
class BaseClass {
    protected $shared_data = "Accessible to subclasses";
}

class FriendClass extends BaseClass {
    public function getSharedData() {
        return $this->shared_data; // Direct access via inheritance
    }
}

$friend = new FriendClass();
echo $friend->getSharedData();
?>
Accessible to subclasses

Key Points

  • The debug_backtrace() method has performance overhead
  • Friend simulation is fragile and hard to maintain
  • Consider using protected visibility or interfaces instead
  • PHP's visibility model is designed around inheritance, not friendship

Conclusion

While PHP can simulate friend classes using magic methods and backtrace inspection, it's generally better to use protected properties with inheritance or proper interface design for cleaner, more maintainable code.

Updated on: 2026-03-15T08:45:28+05:30

390 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements