Changing the scope of privacy of PHP class functions

I have an abstract class that extends classes to provide a basic orm function. All the functions that it provides are protected by the class, so it can decide which fields become public for external objects. But lately, I started working with some smaller data classes that do not require such complexity, and will benefit from the fact that the orm editing functions will be publicly available and will not have special functions.

Since the naming convention for functions is sufficient and compact, is there a way to change existing functions to public (without the need for the same class or intermediate extensions) or will I have to use the new traits php function to add an existing class that contains public versions of functions that act What is the level of abstraction for internally protected functions?

EDIT:

For the symptom method, I thought this would help something like this:

 abstract class ORMClass { public function __construct($pk) {} protected function __get($k) {} protected function __set($k,$v) {} protected function save() {} } trait publicORM { public function __get($k) { return parent::__get($k); } public function __set($k,$v) { return parent::__set($k,$v); } public function save() { return parent::save(); } } class myOrm extends ORMClass { use publicORM; protected static $table = 'myTable'; } 

then I could use myOrm like:

 $myOrm = new myOrm(1); $myOrm->foo = 'alice' echo $myOrm->bar; $myOrm->save(); 

without the need:

 public function __get($k) { return parent::__get($k); } public function __set($k,$v) { return parent::__set($k,$v); } public function save() { return parent::save(); } 

which will be specified in the myOrm class

+4
source share
1 answer

Since it was never answered properly, I add Charles in response.

This can be done using the PHP Reflection library built into PHP since version 5. This particular method is pretty hacky:

 <?php abstract class BaseClass { protected function testMe() { echo 'I WORK!'; } } class ConcreteClass extends BaseClass { // Class Code } $method = new ReflectionMethod('BaseClass', 'testMe'); $method->setAccessible(true); $method->invoke(new ConcreteClass()); // Prints 'I WORK!' 

And here is the best method using an intermediate abstract class that extends the base class but uses public methods:

 <?php abstract class BaseClass { protected function testMe() { echo 'I WORK!'; } } abstract class PublicBaseClass extends BaseClass { public function testMe() { parent::testMe(); } } class ConcreteClass extends PublicBaseClass { // Class Code } $obj = new ConcreteClass(); $obj->testMe(); 
+3
source

All Articles