Question:
How to push $param from load() to $data property in class A?
Therefor I can use get_class_vars get_object_vars to load them.
Each time I use load function, it will add $param to $data property.
Example:
<?php
class Test {
public function testing($str) { echo $str; }
}
class A {
public $data = array();
public function load($param) {
array_push($this->data, $param); // not adding $param to $data property
return $param = new $param;
}
}
class B {
public $a;
public function __construct() {
$this->a = new A();
var_dump(get_object_vars($this->a)); // showing empty $data property
}
}
// Usage
$b = new B();
$test = $b->a->load('test');
$test->testing('hello');
Edit:
used get_object_vars($this->a)
get_class_vars only shows default public variables. Use get_object_vars($this->a) instead; this should work.
Related
I have a php ArrayObject
class myObject extends ArrayObject
{
public function __construct()
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
// populate
$this->populateArray();
{
private function populateArray() {
$this['hello'] = null;
$this['hello2'] = null;
$this['hello3'] = null;
}
}
Now when I access the hello element in this way
$myArray = new myObject();
$value = $myArray['hello'];
I would like to trigger a method in the myObject that assigns to $myArray another object before being read.
My medhod should look like this.
private function method($value) {
$this[$value] = new class2();
}
Is there a way to achieve this ?
You can overwritte offsetGet function like this:
public function offsetGet($index) {
$this->someMethod();
return parent::offsetGet($index);
}
private function someMethod()
{
echo "triggered";
}
Then when you run
$x = new myObject;
echo $x['hello'];
Will output
triggered
In someMethod() you can do whatever you want.
so a class:
class ToBeUsed
{
private $a;
public function setSomething($a)
{
$this->a = $a;
}
public function getSomething()
{
return $this->a;
}
}
its beign created and updated:
$obj = new ToBeUsed();
$obj->setSomething('a');
and passed to another object
class UseIt
{
/**
* #var ToBeUsed
*/
private $obj;
public function __construct(ToBeUsed $obj)
{
$this->obj = $obj;
}
public function work()
{
$this->obj->getSomething();
$this->obj->setSomething(); //// !!!!! THIS IS BAD!
}
}
now a classic DI example, except that the passed object should be "dulled" - only some methods are allowed to use. E.g. getSomething() is allowed to use, but setSomething() is not. What pattern / practice can get away with it? There used to be friend classes is C but its Php...
class ToBeUsed
{
private $a;
public function setSomething($a)
{
$dbg = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
if(count($dbg) > 1){
return;
}
$this->a = $a;
}
public function getSomething()
{
return $this->a;
}
}
class UseIt
{
/**
* #var ToBeUsed
*/
private $obj;
public function __construct(ToBeUsed $obj)
{
$this->obj = $obj;
}
public function work()
{
echo $this->obj->getSomething().PHP_EOL; // a
$this->obj->setSomething('b'); // this does nothing
echo $this->obj->getSomething().PHP_EOL; // a
}
}
$obj = new ToBeUsed();
$obj->setSomething('a');
$obj2 = new UseIt($obj);
$obj2->work();
Alternatively, you can perform more complex checks on debug_backtrace() output.
I would probably do something with Interfaces, it doesn't prevent a method form being used. But "they" (whoever they is) would be using it outside of the Interface for $obj.
Like this:
class ToBeUsed implements ToBeUsedInterface
{
private $a;
public function getSomething()
{
return $this->a;
}
public function setSomething($a)
{
$this->a = $a;
}
}
interface ToBeUsedInterface{
public function getSomething();
}
class UseIt
{
/**
* #var ToBeUsed
*/
private $obj;
public function __construct(ToBeUsedInterface $obj)
{
$this->obj = $obj;
}
public function work()
{
$this->obj->getSomething();
$this->obj->setSomething(); //This now exists outside of the interface for $obj
}
}
In terms of IDE's this would prevent the methods from auto-completing as well.
The only other thing I can think of, ( besides the other answer ) would be to set the method to protected and then use ReflectionMethod to change the viability, when you want to use it.
Another Option, is Using Reflection
class ToBeUsed
{
private $a;
public function getSomething()
{
return $this->a;
}
protected function setSomething($a)
{
$this->a = $a;
}
}
$ToBeUsed = new ToBeUsed();
$ReflectionMethod = new ReflectionMethod($ToBeUsed, 'setSomething');
$ReflectionMethod->setAccessible(true);
$ReflectionMethod->invoke($ToBeUsed, 'foo');
echo $ToBeUsed->getSomething();
Outputs:
foo
You can see it live here
And Obviously sense it's protected under normal conditions, it could not be used inside UseIt. If I was going to use this for any amount of code, I would extend or wrap the Reflection class. Just to make the call a bit more concise, like this:
class MyReflector
{
public static function invoke($class, $method, ...$args)
{
$ReflectionMethod = new ReflectionMethod($class, $method);
$ReflectionMethod->setAccessible(true);
$ReflectionMethod->invokeArgs($class, $args);
}
}
$ToBeUsed = new ToBeUsed();
MyReflector::invoke($ToBeUsed,'setSomething', 'foo');
Please note I got all fancy with the variadic ...$arg which is for PHP 5.6+ it just lets you do
MyReflector::invoke($ToBeUsed,'setSomething', 'foo', 'bar');
And $args would be ['foo','bar'] in the first example it's just ['foo'] which can be used for invokeArgs for the second argument which takes an array of arguments to pass on to the actual method.
Need dynamically append method to class.
My code:
<?php
class stdClass1 {
public function __call($method, $arguments) {
return call_user_func_array(Closure::bind($this->$method, $this, get_called_class()), $arguments);
}
}
class stdClass2 {
function stdRunMethod() {
$obj = new stdClass1();
$obj->test = function() {
echo 'a simple function';
};
$obj->test();
$obj2 = new stdClass1();
$obj2->test();
}
}
$obj = new stdClass2();
$obj->stdRunMethod();
Question: why test method run only for first instance of stdClass1 class? How to append this method for all new instances?
try this instead (demo):
<?php
class stdClass1 extends \stdClass
{
private static $addedClosures = array();
public function __set($name, $value)
{
if ($value instanceof \Closure) {
self::$addedClosures[$name] = $value;
}
else {
parent::__set($name, $value);
}
}
public function __call($method, $arguments)
{
if (isset(self::$addedClosures[$method]))
return call_user_func_array(self::$addedClosures[$method], $arguments);
return call_user_func_array($method, $arguments);
}
}
class stdClass2 extends \stdClass
{
function stdRunMethod()
{
$obj = new stdClass1();
$obj->test = function () {
print_r('a simple function');
};
$obj->test();
$obj2 = new stdClass1();
$obj2->test();
}
}
The reason it only runs once is that each copy of stdClass1 maintains their own set of variables. In the following
$obj1 = new stdClass1();
$obj1->a = '1';
$obj2 = new stdClass1();
$obj2->a = '2';
echo $obj1->a;
You'll get the value 1 as the output. Because in most cases they maintain different references. Unless you use the static keyword. Static properties are shared between all instances of the class, and should be used carefully, but that's what you're thinking of. What you're thinking of can be done like this
<?php
class stdClass1 {
private static $methods = [];
public function __call($method, $arguments) {
return call_user_func_array(Closure::bind($this->methods[$method], $this, get_called_class()), $arguments);
}
public function __set($name, $value) {
if (is_callable($value)) {
$this->methods[$name] = $value;
} else {
parent::__set($name, $value);
}
}
}
Here we're using a static, defined property to hold all of the dynamic methods, and we're using the magic __set property to set the methods in to the array.
That being said, dynamically loading methods in to an object is bad. Don't do that
I want to create properties in a class with the names of all of the variables passed to the constructor and with the same values.
I was able to do it with strings:
class test {
public function __construct() {
$args = func_get_args();
foreach($args as $arg) {
$this->{$arg} = $arg;
$this->init();
}
}
public function init() {
echo $this->one;
}
}
// Output: "one"
$obj = new test("one");
But I don't know how I can do it with variables. I tried this:
class test {
public function __construct() {
$args = func_get_args();
foreach($args as $arg) {
$this->{$arg} = $arg;
$this->init();
}
}
public function init() {
echo $this->one;
}
}
$one = "one!";
$obj = new test($one);
Output:
Notice: Undefined property: test::$one on line 13
What I wanted it to output:
one!
Try:
public function init() {
echo $this->{'one!'};
}
No, it's not possible in any sane way to get the name of a variable used in calling code inside the callee. The sanest method is to use new test(compact('one')), which gives you a regular key-value array inside test::__construct, which you can loop through.
http://php.net/compact
I have an array of reflectionClasses.
I need to get a reflectionObject from one of these and then call its constructor with some parameters.
The point is to instantiate an object without knowing the class name (i'll know it at runtime).
Example, just to render the idea:
foreach (Conf::get_array() as $reflection_class) {
//it's not right, just to render the idea
$reflectionObject = new ReflectionObject ($reflection_class);
$objects[] = $reflectionObject->construct($param_1, $param_2);
}
Another example:
foreach (Conf::get_array() as $reflection_class) {
$objects[] = new $reflection_class($param_1, $param_2); //not right. maybe from php 5.3?
}
You don't need an instance of ReflectionObject for that. ReflectionClass has the two methods
public stdclass newInstance(mixed args)
public stdclass newInstanceArgs(array args)
example:
<?php
class Foo {
public function __construct($a, $b) { echo "Foo($a,$b) "; }
}
class Bar {
public function __construct($a, $b) { echo "Bar($a,$b) "; }
}
class Conf {
public static function get_array() {
return array(new ReflectionClass('Foo'), new ReflectionClass('Bar'));
}
}
$args = array('A', 'B');
$object = array();
foreach (Conf::get_array() as $reflection_class) {
$objects[] = $reflection_class->newInstanceArgs($args);
}
var_dump($objects);