PHPUnit Mocking class constant - php

I am testing a class that has a dependency injected. In my infinite cleverness, I scattered references to the dependency's class constant throughout my code.
(Sorry for the stupid example, wanted to deviate from foobar.)
<?php
class Book_PhoneBook extends Book {
private $author;
public function __construct(Author $author) {
$this->author = $author;
}
public function getCover() {
return $this->author->getTitle(Author::NAME_UNKNOWN) . ' - YELLOW PAGES';
}
}
class Author {
const NAME_UNKNOWN = 'anonymous';
public function getTitle($nameStyle) {
//do complicated calculation of author name
if ($nameStyle == $this::NAME_UNKNOWN) {
$name = "Anonymous";
}
//do further complicated calculations, modifying $name
return $name;
}
}
My problem is with unit tests! I'm getting "Fatal error: Undefined class constant 'NAME_UNKNOWN'" when I mock Author. The whole purpose of mocking is to avoid including the Author class file, so what is the correct way to handle that constant?
I could split Author into several objects or split the method that relies on the constant, but that would incur much repetition.

The fact that you are using the class constant from Author means that you are dependent on having that class available in your code and thus also in your test. So in order to test Book_PhoneBook you need to have an Author class with the constant. If the class constant is going to be a series of flags that you will need to pass to your class, you will need to have the class available and in your test make sure that the original class is loaded. You are dependent on that class for Book_PhoneBook::getCover().
You can also just use the string value of the class constant in your Book_PhoneBook though that sort of defeats the purpose of making it a constant so that you are able to change the value in one place.
With your example, it is a little tricky to get an idea of what you are trying to achieve but since you want to remove the dependency on Author in Book_PhoneBook, I would change it to something like this:
<?php
class Book_PhoneBook extends Book {
private $author;
public function __construct(Author $author) {
$this->author = $author;
}
public function getCover() {
return $this->author->getTitle() . ' - YELLOW PAGES';
}
}
class Author {
const NAME_UNKNOWN = 'anonymous';
public function __construct($nameStyle) {
$this->nameStyle = $nameStyle;
}
public function getTitle() {
//do complicated calculation of author name
if ($this->nameStyle == $this::NAME_UNKNOWN) {
$name = "Anonymous";
}
//do further complicated calculations, modifying $name
return $name;
}
}
This solution does have the problem that adding other options is difficult for getTitle. And without having a better idea of what you are trying to achieve with getTitle, I am not able to offer a better solution.

For anybody having a problem like this in the future, I ended up with this based on #Schleis' answer:
class Author {
const NAME_UNKNOWN = 'anonymous';
private function getTitle($nameStyle) {
//do stuff, taking $nameStyle into account
return $name;
}
public function getAnonymousTitle() {
return $this->getTitle($this::NAME_UNKNOWN);
}
}

Related

Some explanation about calling PHP function in class

I know it is basic php question but I had something that I didn't understand, it is about the return; when I call a function, the bellow code is just an exemple.
Case : In TEST2 when I do my check then I return, that return; do the job and stop the execution of the next code TEST3 Good.
Now in TEST1 I Call a function _checkThat(), and this function do a check then redirect. the problem is it returns shure but the next code will also be executed TEST2 and TEST3 Why ? why when I put the content of that function directly in TEST1 it returns and stop the execution of next code ?
<?php class Some_Class_IndexController extends Some_Other_Controller_Front_Action
{
$name = $this->getRequest()->getParam('name'); //Output: "john"
$email = $this->getRequest()->getParam('email'); //Output: "john#gmail.com"
$phone = $this->getRequest()->getParam('phone'); //Output: 09000000
//TEST1
if(isset($name)) {
$this->_checkThat($name);
}
//TEST2
if(isset($email)) {
if($email === "john#gmail.com") {
//some code to redirect to another page
return;
} else {
//some code to redirect to another page
return;
}
}
//TEST3
if(isset($name)) {
$this->_checkthat();
}
private function _checkThat($name) {
if ($name !== "john") {
//some code to redirect to another page
return;
}
}
}
Other question, Can I use continue; in this case :
if(isset($name)) {
Mage::log('check passed'); //This just write in logs
continue; // or something else
} else if (!isset($name)) {
// some code
}
Although as already mentioned in comments your example code is not correct, your problem here:
if(isset($name)) {
$this->_checkThat($name);
}
is that you do nothing with result returned by _checkThat(). And obviously you should return it:
if(isset($name)) {
return $this->_checkThat($name);
}
As a sidenote, I should mention that naming methods with _ to mark them protected/private is out-of-date practice since php5.
Here is a simple guide.
Inheritance – reusing code the OOP way
Inheritance is a fundamental capability/construct in Object oriented programming where you can use one class, as the base/basis for another class or many other classes.
Why do it?
Doing this allows you to efficiently reuse the code found in your base class.
Say, you wanted to create a new employee class since we can say that employee is a type/kind of `person’, they will share common properties and methods.
Making some sense?
In this type of situation, inheritance can make your code lighter because you are reusing the same code in two different classes. But unlike old-school PHP:
You only have to type the code out once.
The actual code being reused, can be reused in many (unlimited) classes
but it is only typed out in one place conceptually, this is sort-of
like PHP includes().
Take a look at the sample PHP code:
// 'extends' is the keyword that enables inheritance
class employee extends person
{
function __construct($employee_name) {
$this->set_name($employee_name);
}
}
Reusing code with inheritance:
Because the class employee is based on the class person, employee automatically has all the public and protected properties and methods of ‘person’.
Nerd note: Nerds would say that employee is a type of person.
The code:
class employee extends person
{
function __construct($employee_name){
$this->set_name($employee_name);
}
}
Notice how we are able to use set_name() in employee, even though we did not declare that method in the employee class. That is because we already created set_name() in the class person.
Nerd Note: the person class is called (by nerds,) the base class or the parent class because it is the class that the employee is based on. This class hierarchy can become important down the road when your projects become more complex.
Reusing code with inheritance:
As you can see in the code snippet below, we can call get_name on our employee object, courtesy of person.
The code:
<?phpinclude("class_lib.php"); ?>
<?php
// Using our PHP objects in our PHP pages.
$stefan = new person("Stefan Mischook");
echo "Stefan's full name: " . $stefan->get_name();
$james = new employee("Johnny Fingers");
echo "---> " . $james->get_name();
?>
This is a classic example of how OOP can reduce the number of lines of code (don’t have to write the same methods twice) while still keeping your code modular and much easier to maintain.
Overriding methods 1
Sometimes (when using inheritance,) you may need to change how a method works from the base class.
For example, let us say set_name() method in the 'employee' class, had to do something different than what it does in the person class.
You override the person classes version of set_name(), by declaring the same method in employee.
The code snippet:
<?php
class person
{
protected function set_name($new_name) {
if ($new_name != "Jimmy Two Guns") {
$this->name = strtoupper($new_name);
}
}
}
class employee extends person
{
protected function set_name($new_name) {
if ($new_name == "Stefan Sucks") {
$this->name = $new_name;
}
}
}
?>
Notice how set_name() is different in the employee class from the version found in the parent class: person.
<Overriding methods: 2
Sometimes you may need to access your base class’s version of a method you overrode in the derived (sometimes called ‘child’) class.
In our example, we overrode the set_name() method in the employee class. Now I have
used this code:
hperson::set_name($new_name);
to access the parent class’ (person) version of the set_name() method.
The code:
<?php
class person
{
// explicitly adding class properties are optional - but
// is good practice
var $name;
function __construct($persons_name) {
$this->name = $persons_name;
}
public function get_name() {
return $this->name;
}
// protected methods and properties restrict access to
// those elements.
protected function set_name($new_name) {
if ($this->name != "Jimmy Two Guns") {
$this->name = strtoupper($new_name);
}
}
}
// 'extends' is the keyword that enables inheritance
class employee extends person
{
protected function set_name($new_name) {
if ($new_name == "Stefan Sucks") {
$this->name = $new_name;
}
else if ($new_name == "Johnny Fingers") {
person::set_name($new_name);
}
}
function __construct($employee_name)
{
$this->set_name($employee_name);
}
}
?>
Notes: Using the symbol:
::
… allows you to specifically name the class where you want PHP to search for a method:
person::set_name()
… tells PHP to search for set_name() in the person class.
There is also a shortcut if you just want refer to current class’s parent – by using the parent keyword.
The code:
protected function set_name($new_name)
{
if ($new_name == "Stefan Sucks") {
$this->name = $new_name;
}
else if ($new_name == "Johnny Fingers") {
parent::set_name($new_name);
}
}

PHP: Shorthand Switch

I'm looking for more comfortable/more short version of Switch() statement in case of using multiple functions.
I'll give you one example: imagine 100-200 functions in one class, and you want to call only one of them by setting value to id in that class.
In my particular case, I have the following structure of PHP file:
<?php
class _main
{
function request($id)
{
switch($id)
{
case 0:
$this->writeA();
break;
case 1:
$this->writeB();
break;
///...
// then we have 100-200 functions like this in switch.
}
}
function writeA()
{
echo('a');
}
function writeB()
{
echo('b');
}
}
$id = 1;
$x = new _main();
$x->request($id);
?>
For some of you it may seem weird, but I don't want to have that much lines of code with case and break. For me, they are just making code more difficult to read.
(by the way, writing it 100 times will not making it fun for me too).
CONCLUSION
What could be the best,fast and comfortable method?
Can I store functions to array and then call them?
And will it affect performance? Will be Swicth() even faster?
Thank you :)
EDIT
Perhaps there is a different way of thinking/coding and not only array/switch thing.
I can't say I would ever recommend this but if you really want that many methods within a single class and a singular function to route the calls through...
<?php
class MyClass
{
public $id;
public function callFunction()
{
$funcName = 'execute' . $this->id;
return $this->$funcName();
}
private function execute1()
{
echo 'execute1() Called.';
}
private function execute2()
{
echo 'execute2() Called.';
}
}
$c = new MyClass();
$c->id = 1;
$c->callFunction();
Output:
execute1() Called.
I feel like there is most likely another way to approach this with more information utilising Interfaces and Abstract classes, but with the information to go off the above might suffice your requirement.
Edit: Sadly I don't have the time right now to come up with a detailed solution, and I don't really have enough information to go off but perhaps utilising interfaces is your best solution for your requirement. Below is a very quick example.
<?php
interface WritableInterface
{
public function write($data);
}
class VersionOneWriter implements WritableInterface
{
public function write($data)
{
return $data . '<br/>';
}
}
class VersionTwoWriter implements WritableInterface
{
public function write($data)
{
return $data . $data . '<br/>';
}
}
class MyMainClass
{
public function request(WritableInterface $writer, $data)
{
return $writer->write($data);
}
}
$c = new MyMainClass();
$w1 = new VersionOneWriter();
$w2 = new VersionTwoWriter();
echo $c->request($w1, 'DataString');
echo $c->request($w2, 'DataString');
Essentially when you call your request function you pass along a Writer class which implements the WritableInterface. Anything that implements that interface has to have a write() method.
Now when you pass your data across with your method, since you are also passing a writer along that can handle the data you can safely call ->write($data) within your request() method and the result will be dependent on the class you passed through.
If you ever need another method of writing you can just add create another class that implements your interface
Hopefully that made some sense, it was a bit of a ramble as I have to disappear for a bit. If you have any questions I'll try to check back when I have time.
--
Edit2:
The define() in this instance requires PHP7+ since I'm defining an array, but you could prior to PHP7 you could just use a standard array. $classMap = ['FirstClass', 'SecondClass'];
interface MyInterface {}
class FirstClass implements MyInterface {}
class SecondClass implements MyInterface {}
$requestParam = 1;
define('CLASS_MAP', array(
'FirstClass',
'SecondClass',
));
$classMap = CLASS_MAP[$requestParam]; // SecondClass
$class = new $classMap;
var_dump($class); // Dumps out: object(SecondClass)#1 (0) {}

Can you use Dependency Injection and still avoid lots of private variables?

I've been reading / watching a lot of recommended material, most recently this - MVC for advanced PHP developers. One thing that comes up is Singletons are bad, they create dependency between classes, and Dependency Injection is good as it allows for unit testing and decoupling.
That's all well and good until I'm writing my program. Let's take a Product page in a eshop as an example. First of all I have my page:
class Page {
public $html;
public function __construct() {
}
public function createPage() {
// do something to generate the page
}
public function showPage() {
echo $this->html;
}
}
All fine so far, but the page needs a product, so let's pass one in:
class Page {
public $html;
private $product;
public function __construct(Product $product) {
$this->product = $product;
}
public function createPage() {
// do something to generate the page
}
public function showPage() {
echo $this->html;
}
}
I've used dependency injection to avoid making my page class dependent on a product. But what if page had several public variables and whilst debugging I wanted to see what was in those. No problem, I just var_dump() the page instance. It gives me all the variables in page, including the product object, so I also get all the variables in product.
But product doesn't just have all the variables containing all the details of the product instantiated, it also had a database connection to get those product details. So now my var_dump() also has the database object in it as well. Now it's starting to get a bit longer and more difficult to read, even in <pre> tags.
Also a product belongs to one or more categories. For arguments sake let's say it belongs to two categories. They are loaded in the constructor and stored in a class variable containing an array. So now not only do I have all the variables in product and the database connection, but also two instances of the category class. And of course the category information also had to be loaded in from the database, so each category instance also has a database private variable.
So now when I var_dump() my page I have all the page variables, all the product variables, multiples of the category variables in an array, and 3 copies of the database variables (one from the products instance and one from each of the category instances). My output is now huge and difficult to read.
Now how about with singletons? Let's look at my page class using singletons.
class Page {
public $html;
public function __construct() {
}
public function createPage() {
$prodId = Url::getProdId();
$productInfo = Product::instance($prodId)->info();
// do something to generate the page
}
public function showPage() {
echo $this->html;
}
}
And I use similar singletons inside the Product class as well. Now when I var_dump() my Page instance I only get the variables I wanted, those belonging to the page and nothing else.
But of course this has created dependencies between my classes. And in unit testing there's no way to not call the product class, making unit testing difficult.
How can I get all the benefits of dependency injection but still make it easy to debug my classes using var_dump()? How can I avoid storing all these instances as variables in my classes?
I'll try to write about several things here.
About the var_dump():
I'm using Symfony2 as a default framework, and sometimes, var_dump() is the best option for a quick debug. However, it can output so much information, that there is no way you're going to read all of it, right? Like, dumping Symfony's AppKernel.php, or, which is more close to your case, some service with an EntityManager dependency. IMHO, var_dump() is nice when you debugging small bits of code, but large and complex product make var_dump() ineffective. Alternative for me is to use a "real" debugger, integrated with your IDE. With xDebug under PhpStorm I have no real need of var_dump() anymore.
Useful link about "Why?" and "How-to?" is here.
About the DI Container:
Big fan of it. It's simple and makes code more stable; it's common in modern applications. But I agree with you, there is a real problem behind: nested dependencies. This is over-abstraction, and it will add complexity by adding sometimes unnecessary layers.
Masking the pain by using a dependency injection container is making
your application more complex.
If you want to remove DIC from your application, and you actually can do it, then you don't need DIC at all. If you want alternative to DIC, well... Singletons are considered bad practice for not testable code and a huge state space of you application. Service locator to me has no benefits at all. So looks like there is the only way, to learn using DI right.
About your examples:
I see one thing immediately - injecting via construct(). It's cool, but I prefer optional passing dependency to the method that requires it, for example via setters in services config.yml.
class Page
{
public $html;
protected $em;
protected $product;
public function __construct(EntityManager $em) {
$this->em = $em;
}
//I suppose it's not from DB, because in this case EM handles this for you
protected function setProduct(Product $product)
{
$this->product = $product;
}
public function createPage()
{
//$this->product can be used here ONLY when you really need it
// do something to generate the page
}
public function showPage()
{
echo $this->html;
}
}
I think it gives needed flexibility when you need only some objects during execution, and at the given moment you can see inside your class only properties you need.
Conclusion
Excuse me for my broad and somewhat shallow answer. I really think that there is no direct answer to your question, and any solution would be opinion based. I just hope that you might find that DIC is really the best solution with limited downside, as well as integrated debuggers instead of dumping the whole class (constructor, service, etc...).
I exactly know that it's possible to reach result what you wish, and don't use extreme solutions.
I am not sure that my example is good enough for you, but it has: di and it easy to cover by unit test and var_dump will be show exactly what you wish, and i think it encourage SRP.
<?php
class Url
{
public static function getProdId()
{
return 'Category1';
}
}
class Product
{
public static $name = 'Car';
public static function instance($prodId)
{
if ($prodId === 'Category1') {
return new Category1();
}
}
}
class Category1 extends Product
{
public $model = 'DB9';
public function info()
{
return 'Aston Martin DB9 v12';
}
}
class Page
{
public $html;
public function createPage(Product $product)
{
// Here you can do something more to generate the page.
$this->html = $product->info() . PHP_EOL;
}
public function showPage()
{
echo $this->html;
}
}
$page = new Page();
$page->createPage(Product::instance(Url::getProdId()));
$page->showPage();
var_export($page);
Result:
Aston Martin DB9 v12
Page::__set_state(array(
'html' => 'Aston Martin DB9 v12
',
))
Maybe this will help you:
class Potatoe {
public $skin;
protected $meat;
private $roots;
function __construct ( $s, $m, $r ) {
$this->skin = $s;
$this->meat = $m;
$this->roots = $r;
}
}
$Obj = new Potatoe ( 1, 2, 3 );
echo "<pre>\n";
echo "Using get_object_vars:\n";
$vars = get_object_vars ( $Obj );
print_r ( $vars );
echo "\n\nUsing array cast:\n";
$Arr = (array)$Obj;
print_r ( $Arr );
This will returns:
Using get_object_vars:
Array
(
[skin] => 1
)
Using array cast:
Array
(
[skin] => 1
[ * meat] => 2
[ Potatoe roots] => 3
)
See the rest here http://php.net/manual/en/function.get-object-vars.php
The short answer is, yes you can avoid many private variables and using dependency injection. But (and this is a big but) you have to use something like an ServiceContainer or the principle of it.
The short answer:
class A
{
protected $services = array();
public function setService($name, $instance)
{
$this->services[$name] = $instance;
}
public function getService($name)
{
if (array_key_exists($name, $this->services)) {
return $this->services[$name];
}
return null;
}
private function log($message, $logLevel)
{
if (null === $this->getService('logger')) {
// Default behaviour is to log to php error log if $logLevel is critical
if ('critical' === $logLevel) {
error_log($message);
}
return;
}
$this->getService('logger')->log($message, $logLevel);
}
public function actionOne()
{
echo 'Action on was called';
$this->log('Action on was called', 0);
}
}
$a = new A();
// Logs to error log
$a->actionOne();
$a->setService('logger', new Logger());
// using the logger service
$a->actionOne();
With that class, you have just one protected variable and you are able to add any functionality to the class just by adding a service.
A more complexer example with an ServiceContainer can be somthing like that
<?php
/**
* Class ServiceContainer
* Manage our services
*/
class ServiceContainer
{
private $serviceDefinition = array();
private $services = array();
public function addService($name, $class)
{
$this->serviceDefinition[$name] = $class;
}
public function getService($name)
{
if (!array_key_exists($name, $this->services)) {
if (!array_key_exists($name, $this->serviceDefinition)) {
throw new \RuntimeException(
sprintf(
'Unkown service "%s". Known services are %s.',
$name,
implode(', ', array_keys($this->serviceDefinition))
)
);
}
$this->services[$name] = new $this->serviceDefinition[$name];
}
return $this->services[$name];
}
}
/**
* Class Product
* Part of the Model. Nothing too complex
*/
class Product
{
public $id;
public $info;
/**
* Get info
*
* #return mixed
*/
public function getInfo()
{
return $this->info;
}
}
/**
* Class ProductManager
*
*/
class ProductManager
{
public function find($id)
{
$p = new Product();
$p->id = $id;
$p->info = 'Product info of product with id ' . $id;
return $p;
}
}
class UnusedBadService
{
public function _construct()
{
ThisWillProduceAnErrorOnExecution();
}
}
/**
* Class Page
* Handle this request.
*/
class Page
{
protected $container;
/**
* Set container
*
* #param ServiceContainer $container
*
* #return ContainerAware
*/
public function setContainer(ServiceContainer $container)
{
$this->container = $container;
return $this;
}
public function get($name)
{
return $this->container->getService($name);
}
public function createPage($productId)
{
$pm = $this->get('product_manager');
$productInfo = $pm->find($productId)->getInfo();
// do something to generate the page
return sprintf('<html><head></head><body><h1>%s</h1></body></html>', $productInfo);
}
}
$serviceContainer = new ServiceContainer();
// Add some services
$serviceContainer->addService('product_manager', 'ProductManager');
$serviceContainer->addService('unused_bad_service', 'UnusedBadService');
$page = new Page();
$page->setContainer($serviceContainer);
echo $page->createPage(1);
var_dump($page);
You can see, if you look at the var_dump output, that just the services, you called are in the output.
So this is small, fast and sexy ;)

PHP OOP - Pass data between classes through the calling class?

I'm struggling to find a correct approach to pass data between classes, which do not directly call each other, and are only related through a parent class (which I now use, but I consider it a dirty workaround rather than anything near a solution).
I have 3 classes both able to read input and write output, and based on configuration I set one to read, another one to write. It may even be the same class, they all share a parent class, but they are always two separate instances called from a controller class.
Currently I use this sort of functionality:
class daddy {
public static $data;
}
class son extends daddy {
public function setData() {
parent::$data = "candy";
}
}
class daughter extends daddy {
public function getData() {
echo parent::$data;
}
}
while($processALineFromConfig)
$son = new son;
$son->setData();
$daughter = new daughter;
$daughter->getData();
daddy::$data = null; //reset the data, in the actual code $daughter does that in parent::
}
Instantination of these classes runs in a loop, therefore I always need to reset the data after $daughter receives them, 'cos otherwise it would stay there for another pass through the loop.
I'm absolutely sure it's not how class inheritance is supposed to be used, however I'm struggling to find a real solution. It only makes sense the data should be stored in the controller which calls these classes, not the parent, but I already use return values in the setter and getter functions, and I am not passing a variable by reference to store it there to these functions 'cos I have optional parameters there and I'm trying to keep the code clean.
What would be the correct approach to pass data through the controller then?
Thanks!
The best option would be for two object share some other, third object. This would be the class for "third object" which will ensure the exchage:
class Messenger
{
private $data;
public function store($value)
{
$this->data = $value;
}
public function fetch()
{
return $this->data;
}
}
Then a class for both instance, that will need to share some state:
class FooBar
{
private $messenger;
private $name = 'Nobody';
public function __construct($messenger, $name)
{
$this->messenger = messenger;
$this->name = $name;
}
public function setSharedParam($value)
{
$this->messenger->store($value);
}
public function getSharedParameter()
{
return $this->name . ': ' . $this->messenger->fetch();
}
}
You utilize the classes like this:
$conduit = new Messenger;
$john = new FooBar($conduit, 'Crichton');
$dominar = new FooBar($conduit, 'Rygel');
$dominar->setSharedParameter('crackers');
echo $john->getSharedParameter();
// Crichton: crackers
Basically, they both are accessing the same object. This also can be further expanded by making both instance to observe the instance of Messenger.

Design nightmare with PHP

I've been trying for a long time now to find a correct design using PHP to achieve what I want, but everything I've tried failed and I'm guessing it's probably because I'm not looking from the right angle, so I wish some of you can enlighten me and give me some good advice!
The design might seem a little weird at first, but I assure you it's not because I like to make things complicated. For the sake of simplicity I'm only giving the minimal structure of my problem and not the actual code. It starts with these:
<?php
// ------------------------------------------------------------------------
class Mother_A
{
const _override_1 = 'default';
protected static $_override_2 = array();
public static function method_a()
{
$c = get_called_class();
// Uses $c::_override_1 and $c::$_override_2
}
}
// ------------------------------------------------------------------------
class Mother_B extends Mother_A
{
public function method_b()
{
// Uses self::method_a()
}
}
Class Mother_A defines a static method that uses constants and statics to be overridden by children. This allows to define a generic method (equivalent of a "template" method) in the derived class Mother_B. Neither Mother_A or Mother_B are intended to be instanciated, but Mother_B should not be abstract. This exploits Late Static Binding, which I find very useful btw.
Now comes my problem. I want to define two classes, in n distinct 'situations' (situation 1, situation 2, etc):
<?php
// ------------------------------------------------------------------------
class Child_A_Situation_k extends Mother_A
{
// Uses method_a
}
// ------------------------------------------------------------------------
class Child_B_Situation_k extends Mother_B
{
// Uses method_a and method_b
}
Of course I'm not actually giving these stupid names; both classes have different names in each situation, but both follow the same derivation pattern from Mother_A and Mother_B. However, in each individual case ('situation'), both classes need the exact same constants/static override, and I don't know how to do that without duplicating the override manually in both classes.
I tried many things, but the closest I got was to implement an interface Interface_Situation_k that defined constants and statics for the situation k, and make both children implement this interface. Of course, you can't define statics in an interface, so it failed, but you get the idea. I would have traded the interface for a class, but then there's no multiple inheritance in PHP, so it's not valid either. :/ I'm really stuck, and I can't wait to read a possible solution! Thanks in advance!
this is the best i can do, i don't think there is a way to do it with less code.
Look at the comments inside the code for more info.
Fully working code:
<?php
class Mother_A
{
// you're using '_override_1' as a variable, so its obviously not a constant
// also i made it public for the setSituation function,
// you could keep it protected and use reflections to set it
// but i dont really see a reason for that.
// if you want that, look up how to set private/protected variables
public static $_override_1 = 'default';
public static $_override_2 = array();
public static function method_a()
{
$c = get_called_class();
var_dump($c::$_override_1);
var_dump($c::$_override_2);
// Uses $c::_override_1 and $c::$_override_2
}
public static function setSituation($className)
{
$c = get_called_class();
// iterate through the static properties of $className and $c
// and when the you find properties with the same name, set them
$rBase = new ReflectionClass($c);
$rSituation = new ReflectionClass($className);
$staBase = $rBase->getStaticProperties();
$staSituation = $rSituation->getStaticProperties();
foreach($staSituation as $name => $value)
{
if(isset($staBase[$name])) $c::$$name = $value;
}
}
}
// ------------------------------------------------------------------------
class Mother_B extends Mother_A
{
public function method_b()
{
self::method_a();
}
}
class Situation_k
{
public static $_override_1 = 'k';
public static $_override_2 = array('k','k');
}
class Child_A_Situation_k extends Mother_A { }
Child_A_Situation_k::setSituation('Situation_k');
// This is not as short as writing 'extends Mother_A, Situation_k'
// but i think you wont get it shorter
class Child_B_Situation_k extends Mother_B { }
Child_B_Situation_k::setSituation('Situation_k');
echo '<pre>';
Child_A_Situation_k::method_a();
echo "\n";
Child_B_Situation_k::method_a();
echo "\n";
Child_B_Situation_k::method_b();
echo "\n";
echo '</pre>';
?>

Categories