Page 1 of 1

Instantiate protected object

Posted: Tue Feb 06, 2007 10:22 pm
by alex.barylski
Basically I have this:

Code: Select all

class MyClass{
  final protected function __construct()
  {

  }
}
I need to find a hack (without extensions) to instantiate the object using a method other than traditional instantiation...

Code: Select all

$obj = new MyClass;
Can anyone think of anyway to accomplish this?

Here is the real kicker...the above class is actually the base class, which is derived from...so I won't even see that class, what I will see (when included) will be something like:

Code: Select all

class MyClass2 extends MyClass{
  function HelloWorld()
  {
    echo 'Say hello';
  }
}
So I won't even be able to open the class file with fopen(), strip the protected modifier and send the code to eval()...

Any ideas???

Posted: Tue Feb 06, 2007 10:29 pm
by feyd
Why on earth would you need to fopen() the file filter out the constructor and eval() it?

Why is the constructor protected?

Posted: Tue Feb 06, 2007 10:36 pm
by alex.barylski
It's hard to explain without going into much detail...but it's an idea for framework I've been working on....similar to MFC but web based for PHP.

Sometimes you need the framework to handle object creation to keep your client developers from screwing anything up...

Basically, I have a function, which I need external access to, but it must remain protected, as I don't want anyone ever calling this function but the framework - people shouldn't be able to instantiate the object because it's only real use is with the framework and if they call a function (indirectly or on purpose) it'll throw everything out of wack...

Forcing the ctor() private or protected prevents anyone from instantiating the class directly and keeping certain methods protected prevents them from calling those methods when they aren't supposed too...

The dance of objects must remain synchronized otherwise all hell could break loose :P

Cheers :)

Posted: Tue Feb 06, 2007 10:39 pm
by alex.barylski
Just to note, my first mentioned method won't work...cause the object would still have have protected members which need to remain protected...

I also considered trying to somehow dynamically rebuild the object using get_class_methods, etc but that won't work either...

Posted: Wed Feb 07, 2007 12:29 am
by feyd
Why not have a static factory method that can perform a quick access control check (via debug_backtrace())?

Posted: Wed Feb 07, 2007 3:42 am
by Ollie Saunders
I think you are making work for yourself here Hockey. Just make the constructor public and be done with it.