Ok I have a string...
$a_string = "Product";
and I want to use this string in a call to a object like this:
$this->$a_string->some_function();
How the dickens do I dynamically call that object?
(don't think Im on php 5 mind)
So you the code you want to use would be:
$a_string = "Product";
$this->$a_string->some_function();
This code implies a few things. A class called Product with the method some_function(). $this has special meaning, and is only valid inside a class definition. So another class would have a member of Product class.
So to make your code legal, here's the code.
class Product {
public function some_function() {
print "I just printed Product->some_function()!";
}
}
class AnotherClass {
public $Product;
function __construct() {
$this->Product = new Product();
}
public function callSomeCode() {
// Here's your code!
$a_string = "Product";
$this->$a_string->some_function();
}
}
Then you can call it with this:
$MyInstanceOfAnotherClass = new AnotherClass();
$MyInstanceOfAnotherClass->callSomeCode();
I seem to have read this question differently from everyone else who's responded, but are you trying to use variable variables?
In the code you've shown, it looks like you're trying to call a function from string itself. My guess is that you want to call a function from a class with the same name as that string, in this case "Product."
This is what that would look like:
$this->Product->some_function();
It seems you might instead be looking for something like this:
$Product = new Product();
$Product->some_function();
EDIT: You need to be running PHP5 in order to do any method chaining. After that, what you have is perfectly legal.
Let's see if I got your intentions correctly...
$some_obj=$this->$a_string;
$some_obj->some_function();
So you've got an object, and one of it's properties (called "Product") is another object which has a method called some_function().
This works for me (in PHP5.3):
<?PHP
class Foo {
var $bar;
}
class Bar {
function some_func(){
echo "hello!\n";
}
}
$f = new Foo();
$f->bar = new Bar();
$str = 'bar';
$f->$str->some_func(); //echos "hello!"
I don't have PHP4 around, but if it doesn't work there, you might need to use call_user_func() (or call_user_func_array() if you need to pass arguments to some_function()
Related
I want to access testProperty in the below example, but this is inside a nested function (extending twig, it has to be nested), but it of course says
"Using $this when not in object context".
I simply can't open another 'public function' inside an existing one. Does anyone know how to fix this?
I want a global variable in the entire class, without using global.
class test
{
private testProperty;
public function testFunction() {
function abc() {
var_dump($this->testProperty)
}
}
}
I didn't fix the problem exactly as I wanted it stated, but I did fix it in my document. I placed my function outside and made it public and just changed al my abc() to $this->abc() really dumb oversight of mine
If my guess of what you're trying to achieve is correct, you may want to do something like this:
class test
{
private $testProperty = "whatever";
public function testFunction() {
$abc = function() {
var_dump($this->testProperty);
};
$abc();
}
}
$x = new test;
$x->testFunction();
Since $abc is now an anonymous function, it has $this variable available when used inside a class method.
The code above will output:
string(8) "whatever"
Using as an example the class defined here
class Testclass {
private $testvar = "default value";
public function setTestvar($testvar) {
$this->testvar = $testvar;
}
public function getTestvar() {
return $this->testvar;
}
function dosomething()
{
echo $this->getTestvar();
}
}
$Testclass = new Testclass();
$Testclass->setTestvar("another value");
$Testclass->dosomething();
I would like to add inside a function "one more value", like this:
function test_function() {
$Testclass->setTestvar("one more value");
}
But it doesn´t work. I gives the error message undefined variable Testclass. In order to make it work, I have to define the variable as global within the function, like this:
function test_function() {
global Testclass;
$Testclass->setTestvar("one more value");
}
I am quite new to PHP, but it seems rather strange to me this way of using it. From the main PHP file it´s already defined, but when I use it from a function I have to define again.Basically what I am trying to do is to create a class that creates a new file and adds strings to it from different functions. Is there not a better way? Any suggestions? Many thanks in advance.
One way is to use singleton
MyClass::getInstance()->doSomethingUsefull();
Sometimes you can use static method
MyClass::doIt();
Functions have their own private variable scope. So (for example) you can use $i in a function without worrying about it screwing up another $i somewhere else in the program. If you want to have a function perform actions on an already-existing object, just pass the object as a parameter to the function:
function test_function(Testclass $testclass)
{
$testclass->setTestvar("one more value");
}
Then call it with your object:
$Testclass = new Testclass();
test_function($Testclass);
Note: If the functions you're defining outside the class are tightly related to the class, then you probably want to define them as methods inside the class instead of separate stand-alone functions.
I need to create a property called "aip-aup" in a class but I can't get it to work.
First tried to put it up with the property definitions. Unfortunately bracketed property-definitions are not allowed.
This fails (in the __construct()):
$this->${'aip-aup'} = array();
Gives error "Undefined variable 'aip-aup'".
This as well (in the __set method):
$this->${'aip-aup'}[$property] = $value;
Also tried creating a custom helper method, but does absolutely nothing:
$this->createProperty('aip-aup', array());
Any help here?
The property has to be public so should be doable?
If you need doing something like this, then you are doing something wrong, and it would be wise to change your idea, than trying to hack PHP.
But if you have to, you can try this:
class Test {
public $variable = array('foo'=>'bar');
public function __get($name){
if ($name == 'aip-aup'){
return $this->variable;
}
}
}
$test = new Test();
$func = 'aip-aup';
$yourArray = $test->$func;
echo $yourArray['foo'];
I have a class that generates data based on a few things. I would like to format that data from the outside. So I am trying to pass a function into the class so that it would format that data. I have looked at many examples, but it seems this is unique.
Can anybody give an idea of how to do this? The following code gives an error.
<?php
class someClass {
var $outsideFunc; // placeholder for function to be defined from outside
var $somevar='Me'; // generated text
function echoarg($abc){
$outsideFunc=$this->outsideFunc; // bring the outside function in
call_user_func($outsideFunc,$abc); // execute outside function on text
echo $abc;
}
}
function outsidefunc($param){ // define custom function
$param='I am '.$param;
}
$someClass=new someClass();
$someClass -> outsideFunc = 'outsideFunc'; // send custom function into Class
$someClass -> echoarg($someClass->somevar);
$someClass -> outsidefunc = 'outsidefunc';
In PHP, function names are not case sensitive, yet object property names are. You need $someClass->outsideFunc, not $someClass->outsidefunc.
Note that good OOP design practice calls for the use of getter and setter methods rather than just accessing properties directly from outside code. Also note that PHP 5.3 introduced support for anonymous functions.
Yeah. You are right. Now there is no error. But it does not work either.
By default, PHP does not pass arguments by reference; outsidefunc() does not actually do anything useful. If you want it to set $param in the caller to something else, and do not want to just return the new value, you could change the function signature to look like this:
function outsidefunc(&$param) {
You would also need to change the way you call the function, as call_user_func() does not allow you to pass arguments by reference. Either of these ways should work:
$outsideFunc($abc);
call_user_func_array($outsideFunc, array(&$abc));
Why not pass your function as an argument?
<?php
class someClass {
public $somevar="Me";
public function echoarg($abc,$cb=null) {
if( $cb) $cb($abc);
echo $abc;
}
}
$someClass = new someClass();
$someClass->echoarg($someClass->somevar,function(&$a) {$a = "I am ".$a;});
i am not sure what exactly you are looking for, but what i get is, you want to pass object in a function which can be acheive by
Type Hinting in PHP.
class MyClass {
public $var = 'Hello World';
}
function myFunction(MyClass $foo) {
echo $foo->var;
}
$myclass = new MyClass;
myFunction($myclass);
OP, perhaps closures are what you're looking for?
It doesn't do EXACTLY what you're looking for (actually add function to class), but can be added to a class variable and executed like any normal anonymous function.
$myClass->addFunc(function($arg) { return 'test: ' . $arg });
$myClass->execFunc(0);
class myClass {
protected $funcs;
public function addFunc(closure $func) {
$this->funcs[] = $func;
}
public function execFunc($index) { $this->funcs[$index](); } // obviously, do some checking here first.
}
I'm using PHPs create_function($args, $code) function to dynamically load a function definition from a database.
The way I'm attempting to implement it is as follows:
I have a class MyClass which has an instance variable myFunction. The constructor populates that instance variable with the result of a call to create_function. I'm hoping to dynamically create a function for the specific object (once instantiated) of this class, that can be called as $object->myFunction(arg1, arg2);
So my class looks like:
class MyClass {
public $myFunction = '';
public function __construct() {
$this->myFunction = //return function body from DB call.
}
}
I'm then trying to call this dynamic function from elsewhere in my program on the instantiated "MyClass" object by doing something like...
$object = new MyClass();
$object->myFunction(args..);
However I keep getting errors such as:
MyClass and its behaviors do not have a method or closure named myFunction.
When I run var_dump($object->myFunction) I get back "lambda_xx", which is a good sign meaning create_function is at least working.
Interesting Update on Works vs. Doesn't Work cases
It turns out that in my "other file" where I am doing the following:
$pm = Yii::app()->user->postMatching; //This is a PostMatching object made elsewhere
$c = $pm->findRelated;
foreach ($posts as $post) {
var_dump($c);
$postIds = $c($post, $limit);
//post to related mapping
$specificRelatedPostIds[$post->postId] = $postIds;
}
exit; // exiting for testing
This doesn't work, but if instead of pulling the object $pm from Yii::app()->user->postMatching I just create a new one:
$pm = new PostMatching();
$c = $pm->findRelated; //the anon function instance variable
$c(); // THIS WORKS NOW!
So naturally I var_dumped $pm and $c in both the "newly created" case and the case where I get it from Yii::app()->user->postMatching, and they are identical. The only thing that is different is the name of the anonymous function (as expected).
Does anyone have any idea why this might be the case? In both cases $pm IS an instantiated PostMatching object with that instance variable, I'm just unable to use the syntax to invoke it!
Just updated the above with newly discovered "Twists", thanks guys!
Maybe something along these lines can be useful:
class MyClass {
private $myFunction = '';
public function __construct() {
$this->myFunction = //return function body from DB call.
}
public function myFunction() {
$args = func_get_args();
return call_user_func_array($this->myFunction, $args);
}
}
That's due to parsing-related troubles that PHP has. This version should work:
$object = new MyClass();
$method = $object->myFunction;
$method(args..);
See it in action.
You can call the method like this:
call_user_func($object->myFunction, args..);