Array to string conversion - Variable function name calling - php

I need to call some functions inside a class; based on variables, something like this:
$x->$y();
But, I found a strange behavior, consider the following sample code:
$arr = array(
"some_index" => "func_name"
);
$str = "func_name";
class some_class {
public function func_name() {
echo "It works in class!";
}
}
$some_obj = new some_class();
$some_obj->$arr['some_index']();
$some_obj->$str();
Now the line
$some_obj->$arr['some_index']();
gives the errors:
Array to string conversion in ...
Undefined property: some_class::$Array in ...
Uncaught Error: Function name must be a string in...
But, the line
$some_obj->$str();
works perfectly.
Also, both the lines will work, if the function is not defined inside a class.
Anyone knows why this is happening ?

You should call it this way:
$some_obj->{$arr['some_index']}();
here's a living example

Related

PHP calling a class method with class name as variable string

I have a class from which I want to call a function, but the instantiated class variable is taken from a string.
class Myclass
{
public function myFunction($param1,$param2) {
return 'blah';
}
}
I am trying the following but it doesn't work. Errors from log file below.
$myclass='myclass';
${$myclass}=new ucfirst($myclass);
$args=array($stringvar,1);
$retval=call_user_func_array(array(${$myclass}, 'myFunction'), $args);
What am I doing wrong ?
Errors :
PHP Warning: call_user_func_array() expects parameter 1 to be a valid callback, first array member is not a valid class name or object in file.php on line 100
PHP Notice: Undefined variable: myclass in file.php on line 134
PHP Fatal error: Call to a member function myFunction() on a non-object in file.php on line 134
You're overcomplicating it a bit with the extra ${} bracketing on the class reference.
$myclass='myCLaSs';
$myObject = new $myclass();
$retval = $myObject->myFunction($stringvar, 1);
Or if you need to use call_user_func_array:
$args=array($stringvar,1);
$retval=call_user_func_array(array($myObject, 'myFunction'), $args);
When you use the ${} bracketing, you are referencing variables by a variable name. For example:
$myVariable = "A";
$aVariableThatIsHoldingAVariableName = "myVariable";
echo ${$aVariableThatIsHoldingAVariableName}; // outputs "A".
Applying this to your code shows the following logic happening:
Set the variable $myclass equal to the string 'myclass'
$myclass='myclass';
Set the variable ${$myclass}:
This gets the value of the variable $myclass ('myclass') and uses that as the variable name. In other words, the following variable name resolution happens: ${$myclass} => ${'myclass'} => $myclass.
So this line sets $myclass to a new Myclass(); object:
${$myclass}=new ucfirst($myclass);
The first parameter to call_user_func_array is a callable (See http://us2.php.net/manual/en/language.types.callable.php). The callback it looks like you are trying to reference here is Type 3: array($object, $method). But the same variable resolution happens. Now, ${$myclass} is going to resolve differently, because the value of $myclass is a Myclass Object. Variable names have to be strings, not objects (obviously), so ${Myclass Object} is totally invalid.
$args=array($stringvar,1);
$retval=call_user_func_array(array(${$myclass}, 'myFunction'), $args);
But since $myclass at that point is an object already, you can just do the following (as mentioned initially above):
$retval=call_user_func_array(array($myclass, 'myFunction'), $args);

calling class object from other class Not using "global" php

I am new to php so please excuse my lack of knowledge. I am using eclipse and have a project with 3 files inside the project. I am creating a find discount class which takes the class object to call a function from another class. The error:
Notice: Undefined variable: GetInfoClass line ..
Fatal error: Call to a member function getAge() on a non-object line ...
I tried to read about it but I cant seem to understand it. Please help. Thanks
formResponse:
include "GetInfo.php";
include "IfDiscount.php";
$IfDiscount= new IfDiscount();
echo $IfDiscount->findDiscount();
class IfDiscount:
class IfDiscount
{
public function findDiscount(){
$Age = $GetInfoClass->getAge();
echo $Age;}}
$GetInfoClass is not available to findDiscount() because it is out of scope. You should pass it to findDiscount() as a parameter to make it available to that method:
public function findDiscount($GetInfoClass){
$Age = $GetInfoClass->getAge();
return $Age;
}
echo $IfDiscount->findDiscount($GetInfoClass);
(You also want to return $Age, not echo it. You already explicitly echo it when you call that method.)

Using class name from a static constant statically in PHP

I have the class name Car stored as a static variable in constants. I would like to use this constant to call the function a. One options is to use an intermediate variable $tmp. I could then call $tmp::a(). Is there a way to do this in one statement? My attempt is below.
class Car{
public static function a(){
return 'hi';
}
}
class Constants{
public static $use='Car';
}
$tmp=Constants::$use;
echo(${Constants::$use}::a());
IDEOne link
Output is as follows
PHP Notice: Undefined variable: Car in /home/mU9w5e/prog.php on line 15
PHP Fatal error: Class name must be a valid object or a string in /home/mU9w5e/prog.php on line 15
There is always call_user_func():
echo call_user_func( array( Constants::$use, 'a'));
IDEOne Demo
The only alternative that I could find to #nickb's way was using something I've never heard of, but hey that's what SO is for!
I found the ReflectionMethod, which seems to be more bloated than the call_user_func, but was the only alternative way that I could find:
<?php
class Car{
public static function a(){
return 'hi';
}
}
class Constants{
public static $use='Car';
}
$reflectionMethod = new ReflectionMethod(Constants::$use, 'a');
echo $reflectionMethod->invoke(new Car());
The above is a bit of a failed experiment as Casebash doesn't want to create temp variables.
As CORRUPT mentioned in the comments, it is possible to use the following although was tested on PHP version 5.4.14 (which I am unable to do):
echo (new ReflectionMethod(Constants::$use, 'a'))->invoke(new Car());
I have crazy solution, but you should never use it :^ )
echo ${${Constants::$use} = Constants::$use}::a();

PHP - undefined array

the class below is part of an mvc structure im building for my website. the class is there to produce a page if index.php is called without any request in the url. if that is good practice or not I do not know. Im new to php, and this is the first time i implement an mvc structure.
<?php
class Default_Model
{
private $defaultPage = array
(
'headline' => 'JOBBSĂ–KAREN',
'instruction' => 'logga in nedanför'
);
public function __construct()
{
}
public function getContent()
{
line 17 return $defaultPage;
}
}
?>
here is the error message:
Notice: Undefined variable: defaultPage in /home/mengus/dev/www/models/default.php on line 17
so what I dont get is why the array is undefined. I use similar code in other classes and it works just fine. is it a scope issue? I seem to have gone error blind from staring at this :)
thanks for help.
To access the fields you need to use $this and -> operator
return $this->defaultPage;

Function name in Array

I have a problem in calling a function that the name is being stored in an array.
class tempClass {
function someFunction() {
$tempArray = array('functionName' => 'tempFunction');
$tempArray['functionName']();
}
function tempFunction() {
echo "inside function";
}
}
It gives me an error:
"Fatal error: Call to undefined function tempFunction() in /..... line..".
Line number is the line where the function is being called, $tempArray['functionName']();
But if called the method_exists(), it shows that the method is exists. It is very confusing. Can anyone please help me out? Thanks.
Use call_user_func() , like this:
call_user_func($tempArray['functionName']);
UPDATE:
As you want to call a method of a class from inside that class, use the following instead:
call_user_func(array($this, $tempArray['functionName']));
See working demo
Well you ask if the method exists inside the class or object, but you call it without that scope. That won't work...
Try this instead:
call_user_method($tempArray['functionName'],$this);
Just saw that call_user_method() is depreciated. Use call_user_func() as answered by Nelson instead.

Categories