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.
Related
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
This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
So I'm refactoring my code to implement more OOP. I set up a class to hold page attributes.
class PageAtrributes
{
private $db_connection;
private $page_title;
public function __construct($db_connection)
{
$this->db_connection = $db_connection;
$this->page_title = '';
}
public function get_page_title()
{
return $this->page_title;
}
public function set_page_title($page_title)
{
$this->page_title = $page_title;
}
}
Later on I call the set_page_title() function like so
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
When I do I receive the error message:
Call to a member function set_page_title() on a non-object
So what am I missing?
It means that $objPage is not an instance of an object. Can we see the code you used to initialize the variable?
As you expect a specific object type, you can also make use of PHPs type-hinting featureDocs to get the error when your logic is violated:
function page_properties(PageAtrributes $objPortal) {
...
$objPage->set_page_title($myrow['title']);
}
This function will only accept PageAtrributes for the first parameter.
There's an easy way to produce this error:
$joe = null;
$joe->anything();
Will render the error:
Fatal error: Call to a member function anything() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/casMail/dao/server.php on line 23
It would be a lot better if PHP would just say,
Fatal error: Call from Joe is not defined because (a) joe is null or (b) joe does not define anything() in on line <##>.
Usually you have build your class so that $joe is not defined in the constructor or
Either $objPage is not an instance variable OR your are overwriting $objPage with something that is not an instance of class PageAttributes.
It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable.
IE
$game = new game;
$game->doGameStuff($gameReturn);
foreach($gameArray as $game)
{
$game['STUFF']; // No longer an object and is now a standard variable pointer for $game.
}
$game->doGameStuff($gameReturn); // Wont work because $game is declared as a standard variable. You need to be careful when using common variable names and were they are declared in your code.
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
looks like different names of variables $objPortal vs $objPage
I recommend the accepted answer above. If you are in a pinch, however, you could declare the object as a global within the page_properties function.
$objPage = new PageAtrributes;
function page_properties() {
global $objPage;
$objPage->set_page_title($myrow['title']);
}
I realized that I wasn't passing $objPage into page_properties(). It works fine now.
you can use 'use' in function like bellow example
function page_properties($objPortal) use($objPage){
$objPage->set_page_title($myrow['title']);
}
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.)
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();
If I have a function called name(), I can check if (name()) {}, and if name() evaluates to true then the body of the if is executed.
But with a class like this:
$miniaturas = new miniaturas();
$miniaturas->thumb($db);
If I try:
if (thumb($miniaturas->thumb($db))) { }
Or this:
if (thumb($db)) {}
I get:
Fatal error: Call to undefined function thumb() .
How can I call this function in a class like I do for functions outside a class?
It's just if ($miniaturas->thumb($db)) { ... }. This is because you defined thumb() as a member function to the class miniaturas, and because it's a member of that class it's not a member of the global namespace.
if (thumb($miniaturas->thumb($db))) {}
Unless you actually have a function named thumb you want
if ($miniaturas->thumb($db)) {}
The extra function call to thumb is what is breaking
try this:
if(function_exists("$miniaturas->thumb"))
in addition to the comment from Neal, the I check for method/function existance using the following php builtin functions:
function_exists: I use this one to see if a plain function exists
if (function_exists('thumb')) {
thumb($db);
}
method_exists: I prefer to use that one if I have to check for "methods" of objects
$miniaturas = new miniaturas();
if (method_exists($miniaturas, 'thumb')) {
$miniaturas->thumb($db);
}
In addition to that you also can use is_callable, which checks whether a function/method is callable ... take a look at
doc for function_exists
doc for method_exists
doc for is_callable
i think you want
if ($miniaturas->thumb($db)) {
// code
}
and the method thumb should return a boolean
The function_exists() function is used to determine whether or not a function exists:
if (function_exists('thumb')){
//...
}