Can I call a function in another PHP script?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
kknight
Forum Newbie
Posts: 4
Joined: Tue Nov 15, 2005 7:45 pm
Location: CA, USA

Can I call a function in another PHP script?

Post 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
User avatar
Nathaniel
Forum Contributor
Posts: 396
Joined: Wed Aug 31, 2005 5:58 pm
Location: Arkansas, USA

Post by Nathaniel »

Possible, yes. I would highly recommend putting your functions in seperate files, though.
ody
Forum Contributor
Posts: 147
Joined: Sat Mar 27, 2004 4:42 am
Location: ManchesterUK

Post 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.';
	}
}
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

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

Post 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.
Post Reply