Reputation: 190
I would like to prevent foo() from being executed by any other class than B. How can I check which class created object A?
<?php
class A
{
public function foo()
{
if (.... B ) // what should be on the dotts?
echo 'I\'m created by class B, which is fine';
else
echo 'Execution of foo() is not allowed';
}
}
class B
{
public function go()
{
$a = new A;
$a->foo();
}
}
class C
{
public function go()
{
$a = new A;
$a->foo();
}
}
$b = new B;
$b->go(); // result: I\'m created by class B, which is fine
$c = New C;
$c->go(); // result: 'Execution of foo() is not allowed'
Upvotes: 2
Views: 1326
Reputation: 212452
A commonly asked question (e.g. How to get called function name in __construct without debug_backtrace), but in a well-designed application it shouldn't be necessary for a class to know where it's being called from, or to prevent being instantiated when requested.
If you need this type of restriction, then make your class a private attribute of the main class that is permitted to access it.
If you absolutely have to do it, pass the caller through as an argument to the method in preference to the horrendously inefficient debug_backtrace method.
Upvotes: 3
Reputation: 97835
Declare foo
in class B
instead and make it private and, optionally, final. Why would want to define in A
a method that can only be called by B
?
Upvotes: 0