Page 1 of 1

Can I call a function in another PHP script?

Posted: Wed Nov 16, 2005 3:51 pm
by kknight
Can I just call a function in another PHP script, instead of evaluating the whole php script.

For example, a.php calls a function foo() in b.php.

b.php is like this:

Code: Select all

<?
      echo "Hello";

      function foo() {
          echo "I am foo.";
      }
  ?>
a.php just wants to call the function foo() in b.php, but don't want to execute echo "Hello"; in b.php. Is it possible in PHP?

Thanks.

HawleyJR:Please use tags when Posting PHP Code In The Forums

Posted: Wed Nov 16, 2005 3:53 pm
by Nathaniel
Possible, yes. I would highly recommend putting your functions in seperate files, though.

Posted: Wed Nov 16, 2005 4:14 pm
by ody
You could create a class in b.php file then call the function you need in a.php i.e.

Code: Select all

require_once('b.php');
$foo = new bar();
$bar->foo();
unset($bar);
and in b.php have:

Code: Select all

class bar
{
	function foo()
	{
		echo 'I am foo.';
	}
}

Re: Can I call a function in another PHP script?

Posted: Wed Nov 16, 2005 4:53 pm
by Jenk
kknight wrote:Can I just call a function in another PHP script, instead of evaluating the whole php script.

For example, a.php calls a function foo() in b.php.

b.php is like this:

Code: Select all

<?
      echo "Hello";

      function foo() {
          echo "I am foo.";
      }
  ?>
a.php just wants to call the function foo() in b.php, but don't want to execute echo "Hello"; in b.php. Is it possible in PHP?

Thanks.

HawleyJR:Please use tags when Posting PHP Code In The Forums
No.

You would need to have the function definition on it's own, or with other function/class definitions and no script.

if a.php consists of:

Code: Select all

<?php

echo "Hello!\n";

function foo ()
{
    echo "I am foo!";
}

?>
and you wanted b.php to use foo(), then you must include a.php:

Code: Select all

<?php

include 'a.php';

foo();

?>
And the output will be:

Code: Select all

Hello!
I am foo!
The 'best practice' is to have your functions in a seperate file from any script, so you can include them at will and they will not ouput anything unless you explicity call upon a function/class to do so.