PHP: extend existing class - php

Is it possible to set the parent of the class? I.e. an instance of the parent class gets instantiated during runtime and then a child class instance extending a certain parent instance gets created. For example:
class A {
var $test = 'default';
}
class B extends A {
public function __contsruct(A $a) {
parent = $a; //does not work
}
}
$a = new A();
$a->test = 'changed';
$b = new B($a);
$b->test == 'changed'; //should be true
I know that I could just $b = new B(); $b->test = 'changed', but that's not what I'm asking about.

A simple way to accomplish this is like so:
class Foo
{
function __construct() {
$this->hello = "Hello";
}
public function sayHello() {
echo $this->hello."!";
}
}
class Bar
{
function __construct(&$foo) {
$this->foo = $foo;
}
public function sayHelloAgain() {
echo $this->foo->sayHello()." Again!";
}
}
$foo = new Foo();
echo $foo->sayHello(); //outputs "Hello!"
$bar = new Bar($foo);
echo $bar->sayHelloAgain(); //outputs "Hello! Again!"

What you've asked for is not possible in base PHP. There are a few ways to do similar things.
You could use the highly experimental runkit extension. The runkit_class_emancipate and runkit_class_adopt functions should work. However, they operate on entire classes, not instances of a class. This probably limits their usefulness for your application.
If you're trying to emulate the expandable class features of other languages, like Ruby and Perl, runkit_method_add and related functions might be more suitable. Again, however, it still operates on entire classes.
The normally accepted "PHP way" to do things like this is via __call. In fact, with anonymous functions in 5.3, you can do something like...
class Bar {
public function say($thing) {
echo "Bar::say says: $thing\n";
}
}
class Foo extends Bar {
private $extensions = array();
public function addExtension($func_name, $func) {
$this->extensions[ $func_name ] = $func;
}
public function __call($func_name, $arguments) {
array_unshift($arguments, $this);
if(array_key_exists($func_name, $this->extensions))
call_user_func_array($this->extensions[ $func_name ], $arguments);
}
}
$f = new Foo();
$anon = function($obj, $string){ $obj->say($string); };
$f->addExtension('example', $anon);
$f->example("Hello, world!");
You'll note in __call and that in creating the anonymous function that the first argument becomes the instance. That's because PHP 5.3's implementation of anonymous functions can't reference $this. That also means that they can't reference protected or private members of the class. This can be corrected by cloning the instance and using Reflection to expose the protected and private members. See this comment on the anonymous function manual page for an example implementation.
Because of limitations of PHP, you can't directly assign an anonymous function to a property and call it. This example will not work:
class WillNotWork {
public $fatal_error;
}
$broken = new WillNotWork();
$anon = function($arg) { echo "I'm about to create a {$arg} error!"; };
$broken->fatal_error = $anon;
$broken->fatal_error("fatal");
// Fatal error: Call to undefined method WillNotWork::fatal_error()

No, because $a is a separate instance than $b.

Related

PHP equivalent for jQuery $.extend()?

Is there anything equivalent in PHP for jQuery's $.extend()?
I want to pragmatically merge/combine/extend classes with other classes and it's properties (including methods) without using late static binding.
class a {}
class b {}
class c {}
$merged = combine(new a(), new b(), new c());
This is not what I am looking for:
class a {}
class b extends a {}
$merged = new b();
There isn't really anything equivalent in PHP, because their object systems are very different.
JavaScript doesn't have real classes like PHP does, its object system is based on prototypes. Methods can be direct properties of the instance, but if there isn't a direct property the prototype chain will be searched to find it. $.extend() automatically copies properties that are inherited from the prototype to the target object, so the result is kind of like an instance of a subclass of all the original classes.
But PHP doesn't have any equivalent to attaching methods directly to objects, so there's no way that a combine() function could merge all the methods from classes of the arguments. An object is an instance of a particular class, and it gets its methods from the class object (and its superclasses) only.
Like #Barmar said, this isn't really a thing in PHP. Workarounds are ugly but I am going to describe two ugly workarounds for whoever want a big laugh. 🙂
Workaround #1 - Extend classes by the use of magic methods in a class. Pros are that the properties and methods can be accessed from one merged object. But under the surface they are not really merged. So setting properties is discouraged and cross accessing properties is a no go.
class extend {
private $_objects;
private $_properties = [];
public function __construct(...$objects) {
$this->_objects = array_reverse($objects);
}
public function &__isset($name) {
return $this->__get($name);
}
public function __get($name) {
foreach ($this->_objects as $object) {
if (isset($object->$name)) {
return $object->$name;
}
}
if (isset($this->_properties[$name])) {
return $this->_properties[$name];
}
return null;
}
public function __set($name, $value) {
foreach ($this->_objects as $object) {
if (isset($object->$name)) {
$object->$name = $value;
return true;
}
}
$this->_properties[$name] = $value;
return true;
}
public function __call($name, $params) {
foreach ($this->_objects as $object) {
if (method_exists($object, $name)) {
call_user_func_array([$object, $name], $params);
}
}
return null;
}
}
Example Objects:
class a {
var $fruit= 'apple';
function foo() { return 'a'; }
}
class b {
var $fruit = 'banana';
function bar() { return 'b'; }
}
Merge Example:
$merged = new extend(new a(), new b());
echo $merged->foo();
echo $merged->bar();
$merged->this = 'that';
echo $merged->this;
Workaround #2 - Merging objects with anonymous functions instead of methods makes them portable and mergeable. Cons are it may be considered unethic or a future security risk to rely on them.
Anonymous functions in properties can not be defined in the class, but must be set in __construct(). And accessing anonymous functions as properties conflicts the syntax for calling regular methods. So a workaround for the calling syntax is also needed (PHP 7.0+).
Example Objects:
class a {
var $fruit = 'apple';
function __construct(){
$this->foo = function() { return 'a'; };
}
}
class b {
var $fruit = 'banana';
function __construct() {
$this->bar = function() { return 'b'; };
}
}
Merge Example:
$merged = (object)array_merge(
get_object_vars(new a()),
get_object_vars(new b())
);
echo ($merged->foo)(); // $class->var() doesn't work for anonymous functions
echo ($merged->bar)();
$merged->fruit = 'orange';
echo $merged->fruit;
Final conclusions: Surely unconventional, mostly ugly. 😁
You might be better off with late static bindings for extending PHP class objects.
class a {}
class b extends a {}
class c extends b {}

PHP call parent class method

class Foo {
protected static $a = 1;
protected $b = 2;
public function func() { return 'foo' . static::$a . $this->b; }
}
class Bar extends Foo {
protected static $a = 3;
protected $b = 4;
public function func() { return 'bar' . static::$a . $this->b; }
}
$obj = new Bar();
$obj->func(); // returns of course 'bar34'
Is there any option in PHP to call func() from Foo class?
In C++ I would cast $obj to Foo and simply call func()
Bar* obj = new Bar();
Foo* obj2 = (Bar*) obj;
obj2->func(); // returns 'foo14';
If you want to get down and dirty with Reflection then it's possible, but I'd strongly argue that this shouldn't be used anywhere near any production code. If you've got an instance of a child class, then you've got it for a reason, and if it's overridden a parent method then that has also happened for a reason.
Assuming you already know all this, then with that disclaimer out of the way, this should work in any remotely recent version of PHP:
class Foo { public function func() { echo 'I am the parent'; } }
class Bar extends Foo { public function func() { echo 'I am the child'; } }
// Create instance of child class
$bar = new Bar;
// Create reflection class
$reflected = new ReflectionClass(get_class($bar));
// Get parent method
$method = $reflected->getParentClass()->getMethod('func');
// Invoke method on child object
$method->invokeArgs($bar, []);
// I am the parent
See https://3v4l.org/NP6j8
This to me looks like a design issue more than anything else.
However if I were to handle this in a way that were easily readable and without rethinking my design I would do:
<?php
class Foo {
public function func() { return 'foo'; }
}
class Bar extends Foo {
public function func() { return 'bar'; }
public function parentFunc() { return parent::func(); }
}
$obj = new Bar();
$obj->parentFunc(); // returns of course 'foo'
Loek's answer also works, but doesn't call the method on the objects parent. It just calls the method on the classes parent. It all depends on the functionality you are looking for.
You could also do something like:
<?php
class Foo {
public function func() { return 'foo'; }
}
class Bar extends Foo {
public function func($parent = false) {
if ($parent) {
return parent::func();
}
return 'bar';
}
}
$obj = new Bar();
$obj->func(true); // returns of course 'foo'
Which is similar but without the need for the extra method.
Personally though I feel this issue likely requires a rethink in code design more than a coding solution.
-- edit --
To elaborate on 'a rethink in code design', I would ask myself "Why do I need an object that has two methods with the same name, but different functionalities? Is this not a job for two different objects? Trace the issue backwards until you find the design issue. Or the point at which the decision needs to be made as to which object your framework requires.
This isn't exactly what I'd call pretty, but it works and is relatively similar to what you described for C++; It works by calling get_parent_class() and then abusing PHP's ability to create objects from strings.
<?php
class Foo {
public function func() { echo 'foo'; }
}
class Bar extends Foo {
public function func() { echo 'bar'; }
}
$obj = new Bar();
$obj->func(); // Prints 'bar'
$parentClassString = get_parent_class($obj);
$newObj = new $parentClassString; // Gotta love PHP for magic like this
$newObj->func(); // Prints 'foo'
See this snippet to see it in action.
EDIT
It's a lot of work, but you could use so called Late Static Binding, perhaps more clearly explained in Jokerius's answer here. This requires you to write a crapload of custom code though, which I don't think is preferential. Overall the short answer seems to be: it isn't really possible.
I don't know should it help you but try to add this function in Bar class
public function callParent($function){
return parent::$function();
}
and call
echo $obj->callParent("func");
[UPDATED]
Also you can write cast function yourself
something like this
public function castAs($newClass) {
$obj = new $newClass;
foreach (get_object_vars($this) as $key => $name) {
$obj->$key = $name;
}
return $obj;
}

PHP binding method to another class

Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.
P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class
class Foo {
public $text = 'Hello World!';
public function say() {
echo $this->text;
}
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable(array(new Foo, 'say'));
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
Code below works fine
function say(){
echo $this->text;
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable('say');
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).
So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable.
This means, you have two options to fix your problem:
Bar must be compatible with the type of Foo - so just make Bar
extend from Foo, if possible.
Use unbound functions, like annonymous, static or functions outside of classes.
It is not supported by PHP. However in PHP 7.0 it was kinda possible. Consider this example:
class Foo {
private $baz = 1;
public function baz() {
var_dump('Foo');
var_dump($this->baz);
}
}
class Bar {
public $baz = 2;
public function baz() {
var_dump('Bar');
var_dump($this->baz);
}
}
$fooClass = new ReflectionClass('Foo');
$method = $fooClass->getMethod('baz');
$foo = new Foo;
$bar = new Bar;
$closure = $method->getClosure($foo);
$closure2 = $closure->bindTo($bar);
$closure2();
The output of foregoing code is:
string(3) "Foo"
int(2)
And this means method Foo::baz was called on object $bar and has accessed its $baz property rather than Foo::$baz.
Also, please note that Bar::$baz is public property. If it was private, php would throw Fatal error cannot access private property. This could've be fixed up by changing the scope of closure $closure->bindTo($bar, $bar);, however doing this was already prohibited in php7.0 and would lead to a following warning: Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure().
There's workaround however, which will work for latest versions of php. Laravel created a splendid package called laravel/serializable-closure. What it does is simple - it reads source code of closure in order to serialize it and be able to unserialize it later with all necessary context.
So basically the functionality of unserialized closure remains the same, however it is different from PHP's perspective. PHP doesn't know it was created from class method and therefore allows to bind any $this.
Final variant will look like this:
$callback = [$foo, 'baz'];
$closure = unserialize(
serialize(new SerializableClosure(Closure::fromCallable($callback)))
)->getClosure();
$closure->call($bar);
Please, note that serialization and unserialization are expensive operations, so do not use provided solution unless there's no other solution.

calling a class function from another class function

I'm new to programming. I have this going on:
I have Class A, which have many functions. One of those functions is functionX.
In functionX I need to make a call to functionY which belongs to another class: Class B.
So how do I acces to functionY from inside functionX?
I use Codeigniter.
Thanks in advance.
Try and experiment with this.
class ClassA {
public function functionX() {
$classB = new ClassB();
echo $classB->functionY();
}
}
class ClassB {
public function functionY() {
return "Stahp, no more OO, stahp!";
}
}
Class function? A static method?
If you have an instance (public) method, you just call $classB->functionY().
If you have a static method, you would call ClassB::functionY();
So:
class ClassA {
public function functionX(){
$classB = new ClassB();
// echo 'foo';
echo $classB->functionY();
// echo 'bar';
echo ClassB::functionYStatic();
}
}
class ClassB {
public $someVar;
public static $someVar2 = 'bar';
function __construct(){
$this->someVar = 'foo';
}
public function functionY(){
return $this->someVar;
}
public static function functionYStatic(){
return self::$someVar2;
}
}
Well that depends. If that function is a static function or not.
First off you must include the file with the class...
include_once('file_with_myclass.php');
If it is static you can call it like this:
ClassName::myFunction()
If it is not, then you create an instance of the class and then call the function on that instance.
$obj = new ClassName();
$obj->myFunction();
As you can guess the function being static means you can call it without the need of creating an instance. That is useful for example if you have a class Math and want to define a function that takes to arguments to calculate the sum of them. It wouldn't really be useful to create an instance of Math to do that, so you can declare as static and use it that way.
Here's a link to the docs with further info
http://www.php.net/manual/en/keyword.class.php
If functionY is static you can call ClassB::functionY(). Else you must create instance of Class B first. Like:
$instance = ClassB;
$instance->functionY();
But maybe you mean something else?
Looks like one of your class has a dependency to another one:
<?php
class A
{
public function x()
{
echo 'hello world';
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function y()
{
$this->a->x();
}
}
$a = new A();
$b = new B($a);
$b->y();
Depending how your code looks like, if it makes sense, you can inject class A into y()
public function y(A $a)
{
// your code with $a
}

How to call the __invoke method of a member variable inside a class

PHP 5.4.5, here. I'm trying to invoke an object which is stored as a member of some other object. Like this (very roughly)
class A {
function __invoke () { ... }
}
class B {
private a = new A();
...
$this->a(); <-- runtime error here
}
This produces a runtime error, of course, because there's no method called a. But if I write the call like this:
($this->a)();
then I get a syntax error.
Of course, I can write
$this->a->__invoke();
but that seems intolerably ugly, and rather undermines the point of functors. I was just wondering if there is a better (or official) way.
There's three ways:
Directly calling __invoke, which you already mentioned:
$this->a->__invoke();
By assigning to a variable:
$a = $this->a;
$a();
By using call_user_func:
call_user_func($this->a);
The last one is probably what you are looking for. It has the benefit that it works with any callable.
FYI in PHP 7+ parenthesis around a callback inside an object works now:
class foo {
public function __construct() {
$this -> bar = function() {
echo "bar!" . PHP_EOL;
};
}
public function __invoke() {
echo "invoke!" . PHP_EOL;
}
}
(new foo)();
$f = new foo;
($f -> bar)();
Result:
invoke!
bar!
I know this is a late answer, but use a combination of __call() in the parent and __invoke() in the subclass:
class A {
function __invoke ($msg) {
print $msg;
}
}
class B {
private $a;
public function __construct() { $this->a = new A(); }
function __call($name, $args)
{
if (property_exists($this, $name))
{
$prop = $this->$name;
if (is_callable($prop))
{
return call_user_func_array($prop, $args);
}
}
}
}
Then you should be able to achieve the syntactic sugar you are looking for:
$b = new B();
$b->a("Hello World\n");

Categories