Ошибка php call to undefined function

I am trying to call a function from another function. I get an error:

Fatal error: Call to undefined function getInitialInformation() 
in controller.php on line 24

controller.php file:

require_once("model/model.php"); 

function intake() {
    $info = getInitialInformation($id); //line 24
}

model/model.php

function getInitialInformation($id) {
    return $GLOBALS['em']->find('InitialInformation', $id);
}

Things already tried:

  1. Verified that the require_once works, and the file exists in the specified location.
  2. Verified that the function exists in the file.

I am not able to figure this out. Am I missing something here?

Eric Leschinski's user avatar

asked Jan 2, 2013 at 1:20

janenz00's user avatar

6

How to reproduce the error, and how to fix it:

  1. Put this code in a file called p.php:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    ?>
    
  2. Run it like this:

    php p.php
    
  3. We get error:

    PHP Fatal error:  Call to undefined function salt() in 
    /home/el/foo/p.php on line 6
    
  4. Solution: use $this->salt(); instead of salt();

    So do it like this instead:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            $this->salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    
    ?>
    

If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.

answered Mar 28, 2014 at 20:59

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

146k95 gold badges412 silver badges332 bronze badges

7

This was a developer mistake — a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long — problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the «undefined function». That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

answered Jan 2, 2013 at 2:04

janenz00's user avatar

janenz00janenz00

3,3155 gold badges28 silver badges37 bronze badges

4

Many times the problem comes because php does not support short open tags in php.ini file, i.e:

<?
   phpinfo();
?>

You must use:

<?php
   phpinfo();
?>

egig's user avatar

egig

4,3155 gold badges29 silver badges50 bronze badges

answered Sep 26, 2013 at 21:08

JRivero's user avatar

JRiveroJRivero

911 silver badge3 bronze badges

I happened that problem on a virtual server, when everything worked correctly on other hosting.
After several modifications I realized that I include or require_one works on all calls except in a file.
The problem of this file was the code < ?php ? > At the beginning and end of the text.
It was a script that was only < ?, and in that version of apache that was running did not work

loki's user avatar

loki

9,7067 gold badges56 silver badges80 bronze badges

answered Aug 30, 2016 at 9:32

Asier Arizti's user avatar

0

This is obviously not the case in this Q,
but since I got here following the same error message I though I would add what was wrong with my code and maybe it will help some one else:

I was porting code from JS to PHP and ended up having a class with some public method.
The code that was calling the class (being code that originated from JS) looked something like:

$myObject.method(...)

this is wrong because in PHP it should look like this:

$myObject->method(...)

and it also resulted with «PHP Call to undefined function».

change to use -> and the problem was solved.

answered Dec 13, 2022 at 5:10

epeleg's user avatar

epelegepeleg

10.3k17 gold badges101 silver badges151 bronze badges

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload[‘helper’] = array(‘common’,’security’,’url’);

common is the name of my controller.

answered Jun 9, 2017 at 10:00

user8136352's user avatar

1

Please check that you have <?PHP at the top of your code. If you forget it, this error will appear.

answered Sep 29, 2020 at 3:32

Hosein Abdollahipoor's user avatar

I am trying to call a function from another function. I get an error:

Fatal error: Call to undefined function getInitialInformation() 
in controller.php on line 24

controller.php file:

require_once("model/model.php"); 

function intake() {
    $info = getInitialInformation($id); //line 24
}

model/model.php

function getInitialInformation($id) {
    return $GLOBALS['em']->find('InitialInformation', $id);
}

Things already tried:

  1. Verified that the require_once works, and the file exists in the specified location.
  2. Verified that the function exists in the file.

I am not able to figure this out. Am I missing something here?

Eric Leschinski's user avatar

asked Jan 2, 2013 at 1:20

janenz00's user avatar

6

How to reproduce the error, and how to fix it:

  1. Put this code in a file called p.php:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    ?>
    
  2. Run it like this:

    php p.php
    
  3. We get error:

    PHP Fatal error:  Call to undefined function salt() in 
    /home/el/foo/p.php on line 6
    
  4. Solution: use $this->salt(); instead of salt();

    So do it like this instead:

    <?php
    class yoyo{
        function salt(){
        }
        function pepper(){
            $this->salt();
        }
    }
    $y = new yoyo();
    $y->pepper();
    
    ?>
    

If someone could post a link to why $this has to be used before PHP functions within classes, yeah, that would be great.

answered Mar 28, 2014 at 20:59

Eric Leschinski's user avatar

Eric LeschinskiEric Leschinski

146k95 gold badges412 silver badges332 bronze badges

7

This was a developer mistake — a misplaced ending brace, which made the above function a nested function.

I see a lot of questions related to the undefined function error in SO. Let me note down this as an answer, in case someone else have the same issue with function scope.

Things I tried to troubleshoot first:

  1. Searched for the php file with the function definition in it. Verified that the file exists.
  2. Verified that the require (or include) statement for the above file exists in the page. Also, verified the absolute path in the require/include is correct.
  3. Verified that the filename is spelled correctly in the require statement.
  4. Echoed a word in the included file, to see if it has been properly included.
  5. Defined a separate function at the end of file, and called it. It worked too.

It was difficult to trace the braces, since the functions were very long — problem with legacy systems. Further steps to troubleshoot were this:

  1. I already defined a simple print function at the end of included file. I moved it to just above the «undefined function». That made it undefined too.
  2. Identified this as some scope issue.

  3. Used the Netbeans collapse (code fold) feature to check the function just above this one. So, the 1000 lines function above just collapsed along with this one, making this a nested function.

  4. Once the problem identified, cut-pasted the function to the end of file, which solved the issue.

answered Jan 2, 2013 at 2:04

janenz00's user avatar

janenz00janenz00

3,3155 gold badges28 silver badges37 bronze badges

4

Many times the problem comes because php does not support short open tags in php.ini file, i.e:

<?
   phpinfo();
?>

You must use:

<?php
   phpinfo();
?>

egig's user avatar

egig

4,3155 gold badges29 silver badges50 bronze badges

answered Sep 26, 2013 at 21:08

JRivero's user avatar

JRiveroJRivero

911 silver badge3 bronze badges

I happened that problem on a virtual server, when everything worked correctly on other hosting.
After several modifications I realized that I include or require_one works on all calls except in a file.
The problem of this file was the code < ?php ? > At the beginning and end of the text.
It was a script that was only < ?, and in that version of apache that was running did not work

loki's user avatar

loki

9,7067 gold badges56 silver badges80 bronze badges

answered Aug 30, 2016 at 9:32

Asier Arizti's user avatar

0

This is obviously not the case in this Q,
but since I got here following the same error message I though I would add what was wrong with my code and maybe it will help some one else:

I was porting code from JS to PHP and ended up having a class with some public method.
The code that was calling the class (being code that originated from JS) looked something like:

$myObject.method(...)

this is wrong because in PHP it should look like this:

$myObject->method(...)

and it also resulted with «PHP Call to undefined function».

change to use -> and the problem was solved.

answered Dec 13, 2022 at 5:10

epeleg's user avatar

epelegepeleg

10.3k17 gold badges101 silver badges151 bronze badges

Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter

$autoload[‘helper’] = array(‘common’,’security’,’url’);

common is the name of my controller.

answered Jun 9, 2017 at 10:00

user8136352's user avatar

1

Please check that you have <?PHP at the top of your code. If you forget it, this error will appear.

answered Sep 29, 2020 at 3:32

Hosein Abdollahipoor's user avatar

Изучаю PHP. Начал писать простенький блог по урокам с geekbrains

function articles_all(){
       //Zapros
        $query = "SELECT * FROM articles ORDER BY id DESC";
        $result = mysqli_query($link, $query);
        
    if (!$result)
        die(mysqli_error($link));
    
    //Izvlekaem iz bd
    $n = mysqli_num_rows($result);
    $articles = array();
        
    for ($i = 0; $i < $n; $i++){
        $row = mysqli_fetch_assoc($result);
        $articles[] = $row;
    }
        return $articles;
}

Fatal error: Call to undefined function articles_all() in C:xampphtdocsblogindex.php on line 6
Ну в индексе вызывается функция. Пожалуйста, объясните проблему, чтоб я понял) Заранее спасибо


  • Вопрос задан

    более трёх лет назад

  • 6472 просмотра

Пригласить эксперта

Файл класса.

<?php
class Articless {
 public function articles_all(){
       //Zapros
        $query = "SELECT * FROM articles ORDER BY id DESC";
        $result = mysqli_query($link, $query);
        
    if (!$result)
        die(mysqli_error($link));
    
    //Izvlekaem iz bd
    $n = mysqli_num_rows($result);
    $articles = array();
        
    for ($i = 0; $i < $n; $i++){
        $row = mysqli_fetch_assoc($result);
        $articles[] = $row;
    }
        return $articles;
}
}

в ndex.php
подключаете:
include(‘classFileName.php’);

используете:

$articles = new Articless();

$articles->articles_all();

Fatal error: Call to undefined function articles_all() in C:xampphtdocsblogindex.php on line 6

Ругается, что ты обращаешся к несуществующей функции в 6ой строчке.
Возможно, ты забыл её за’include’ить?)


  • Показать ещё
    Загружается…

24 июн. 2023, в 22:35

1500 руб./за проект

24 июн. 2023, в 21:49

1000 руб./за проект

24 июн. 2023, в 18:21

30000 руб./за проект

Минуточку внимания

The majority of new web developers see the fatal error “Call to undefined function” in PHP code, and they are unsure of the cause. If you’re one of them, then continue reading this article to the end.

We encounter the uncaught error “Call to undefined function” when we define and call a user-defined function. There are numerous causes for this error, and in this post, we will explore them all and provide easy explanations to dispel all of your doubts.

However, before we go into the details of this article, you need first to comprehend what a function is and what we call it. So without further ado, let’s get started with the post.

Table of Contents
  1. How Do Functions Work in PHP?
  2. What Are the Reasons and Solutions For The “Call to Undefined Function” Fatal Error in PHP?
    1. 1. Misspell of Function Name
    2. 2. Not Using This with Function Name Within PHP Class
    3. 3. Use Include or Require Properly
    4. 4. Using Dot(.) Instead of Object Operator(->)

How Do Functions Work in PHP?

Similar to other programming languages, PHP has functions. A function is a separate code that processes additional input as a parameter before returning a value. In PHP, we have two types of functions Builtin functions and user-defined functions.

Builtin functions are the functions that PHP provides to us to use them. Actually, you seldom ever need to build your own function because there are already more than 1000 built-in library functions available for various purposes; all you need to do is call them as needed.

On the other hand, we can create our own functions, called user-defined functions. In the case of user-defined functions, there are two key aspects you need to understand:

  1. Creating a PHP Function
  2. Calling a PHP Function

Creating your own PHP function is pretty simple. Let’s say you want to create a PHP function that, when called, will display a brief message in your browser. The example below invokes the method printMessage() immediately after creating it.

The name of a function should begin with the keyword “function,” and all PHP code should be enclosed in “{ }” brackets, as seen in the example below:

Code

<html>


   <head>

      <title>PHP Function Page</title>

   </head>

   

   <body>

      

      <?php

         // Creating a PHP Function

         function printMessage() {

            echo "Welcome to My Website";

         }

         

         // Calling a PHP Function

         printMessage();

      ?>

      

   </body>

</html>

Output

Welcome to My Website

What Are the Reasons and Solutions For The “Call to Undefined Function” Fatal Error in PHP?

Following are the reasons for facing the “Uncaught Error: Call to undefined function“:

  1. Misspell of function
  2. Not using this with the function name
  3. Use include or require properly
  4. Using dot(.) instead of object operator(->)

1. Misspell of Function Name

To prevent “Call to undefined function“, always double-check the function name. Let’s look at a straightforward example to see what output the following code will return if the function name is misspelt:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunctions();

?>

In this example, we write myfunctions() in place of myfunction(), which causes this error, so it is always better to double-check the spelling of functions to avoid this error.

2. Not Using This with Function Name Within PHP Class

We face a “call to an undefined function” when we don’t use $this with the function or property name of the class. For example:

Code

<?php

class myclass{

    function printMessage(){

      

    }

    function myfunction(){

        printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunction();

?>

The $this keyword in PHP refers to the class’s current object. Using the object operator (->), the $this keyword gives you access to the current object’s attributes and methods.

Only classes have access to the $this keyword. Beyond the class, it doesn’t exist. You’ll see an error if you try to use $this outside of a class.

You only use the $ with this keyword when you want to access an object property. The property name is not used with the dollar sign ($).

We now rewrite the code that causes the abovementioned errors with this keyword and examines the results:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

$myvar->myfunction();

?>

Output

Welcome to My Website

3. Use Include or Require Properly

When we create a namespace and include it in another file, we often face “Call to undefined function“. For example:

Code of main.php

include myfunction.php

<?php

    echo tempNamespaceprintMessage();

?>

Code of myfunction.php

<?php

    namespace tempNamespace {

        function printMessage() {

            return "Welcome to my Website"

        }

    }

?>

To avoid this error, we have to write include or require statements correctly and in the proper place. Now we write the above code again using the appropriate include statement.

Code of mymain.php

<?php

    include "myfunction.php";

    echo tempNamespaceprintMessage();

?>

Code of myfunction.php

<?php

    namespace tempNamespace {

        function printMessage() {

            return "Welcome to my Website";

        }

    }

?>

Output

Welcome to my Website

Most of the time, when the user doesn’t check the file name, writes the wrong namespace name, or doesn’t include the namespace correctly, then faces “Call to undefined function” in PHP.

4. Using Dot(.) Instead of Object Operator(->)

The PHP code syntax is different from other programming languages. So when you come from JS or any other Object Oriented language, we use the dot(.) operator to call a method on an instance or access an instance property. But in PHP, we access the members of the provided object using the object operator (->). For example:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

// Use . operator in place of object operator ->

$myvar.myfunction();

?>

We can easily get rid of this error by just replacing the dot(.) with the object operator(->). For example:

Code

<?php

class myclass{

    function printMessage(){

      echo "Welcome to My Website";

    }

    function myfunction(){

        $this->printMessage();

    }

}

$myvar = new myclass();

// Use . operator in place of object operator ->

$myvar->myfunction();

?>

Output

Welcome to My Website

Conclusion

Finally, you arrive at a point after finishing this reading when you can quickly get rid of the “Call to undefined function“. We covered all the causes in this article and gave you all the solutions. In this circumstance, we provide you with straightforward examples to help you resolve this uncaught issue.

To summarise the article on “How to fix call to undefined function in PHP“, always first search for the PHP file containing the function definition. Next, confirm the file’s existence and check to see if the page had the necessary (or included) line for the file, as mentioned above. Ensure the absolute path in the require/include is accurate as well.

Double-check that the spelling of the required statement’s filename is correct. Use this keyword in class to refer to the same class function. Always check the syntax of your code; many times, users from different languages use the wrong operators.

Share this article with your fellow coders if you found it beneficial, and let us know in the comments below ⬇️ which solution you used to solve the uncaught error “Call to undefined function”.

Happy Coding! 🥳

  1. HowTo
  2. PHP Howtos
  3. Call to Undefined Function in PHP

Shraddha Paghdar
Oct 24, 2021

Call to Undefined Function in PHP

Many of you have encountered this error several times Fatal error: Call to undefined function function_name(). In today’s post, we are finding out how to unravel this error. But before we solve this problem, let’s understand how PHP evaluates the functions.

There are several ways to define functions and call them. Let’s say you write it in the function.php file and call it in the main.php file.

    // function.php
<?php
    namespace fooNamespace {
        function foo() {
            return "Calling foo"
        }
    }
?>
    // main.php
include function.php
<?php
    echo fooNamespacefoo();
?>

Namespaces are qualifiers that enable better management by grouping classes that work together to perform a task. It allows you to use the same name for multiple classes. It is important to know how PHP knows which element of the namespace is required by the code. PHP namespaces work quite a sort of a filesystem. There are 3 ways to access a file in a file system:

  1. Relative file name such as fooBar.txt. It will resolve to fooDirectory/fooBar.txt where fooDirectory is the directory currently busy directory.
  2. Relative path name such as subdirectory/fooBar.txt. It will resolve to fooDirectory/subdirectory/fooBar.txt.
  3. Absolute path name such as /main/fooBar.txt. It will resolve to /main/fooBar.txt.

Namespaced elements in PHP follow an equivalent principle. For example, a class name can be specified in three ways:

  1. Unqualified name/Unprefixed class name:Or,If the current namespace is foonamespace, it will always resolve to foonamespacefoo. If the code is a global, non-namespaced code, this resolves to foo.
  2. Qualified name/Prefixed class name:
    $a = new fooSubnamespacefoo();
    

    Or,

    fooSubnamespacefoo::staticmethod();
    

    If the present namespace is foonamespace, it will always resolve to foonamespacefooSubnamespacefoo. If the code is global, non-namespaced code, this resolves to fooSubnamespacefoo.

  3. Fully qualified name/Prefixed name with global prefix operator:
    $a = new foonamespacefoo();
    

    Or,

    foonamespacefoo::staticmethod();
    

    This always resolves to the literal name laid out in the code, foonamespacefoo.

Now suppose you define a class & call the method of a class within the same namespace.

<?php
    class foo {
        function barFn() {
          echo "Hello foo!"
        }
        function bar() {
            barFn();
            // interpreter is confused which instance's function is called
            $this->barFn();
        }
    }
    $a = new foo();
    $a->bar();
?>

$this pseudo-variable has the methods and properties of the current object. Such a thing is beneficial because it allows you to access all the member variables and methods of the class. Inside the class, it is called $this->functionName(). Outside of the class, it is called $theclass->functionName().

$this is a reference to a PHP object the interpreter created for you, which contains an array of variables. If you call $this inside a normal method in a normal class, $this returns the object to which this method belongs.

Steps to Resolve the Error of Calling to Undefined Function in PHP

  • Verify that the file exists. Find the PHP file in which the function definition is written.
  • Verify that the file has been included using the require (or include) statement for the above file on the page. Check that the path in the require/include is correct.
  • Verify that the file name is spelled correctly in the require statement.
  • Print/echo a word in the included file to ascertain if it has been properly included.
  • Defined a separate function at the end of the file and call it.
  • Check functions are closed properly. (Trace the braces)
  • If you are calling methods of a class, make sure $this-> is written.

Shraddha Paghdar avatar
Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn

  • Ошибка package e1071 is required
  • Ошибка php artisan migrate
  • Ошибка pab чери фора
  • Ошибка photoshop невозможно выполнить запрос перед маркером jpeg
  • Ошибка pab на zanotti