Mahdi_Nine
Mahdi_Nine

Reputation: 14751

How to call a function in PHP in another form?

I have a page with name 1.php that has a function in it. Now I want to call the function in 2.php in PHP 2. I wrote func(); this function is in 1.php.

But it has this error:

Fatal error: Call to undefined function func() in C:\xampp\htdocs\me\2.php on line 2

How can I do that?

Upvotes: 1

Views: 1055

Answers (1)

Oliver Spryn
Oliver Spryn

Reputation: 17358

Include the script that contains the function you need using the require_once() method, like this:

require_once("../path/to/script.php");

Once you use the above method, PHP basically tacks the included script into the parent script, which will allow you to call functions, methods, and variables, as if they were in the parent script itself.

I would recommend require_once() over include(), include_once(), or require(), because this method will make sure that the script you are looking for exists, and is only called once. Calling the same script more than once (usually happening by accident) can cause strange problems in your script.

I hope that helps.

Upvotes: 5

Related Questions