DixonMD
DixonMD

Reputation: 93

Calling a single function from another file without including the whole file in php

Is it possible to call only the specific function from another file without including whole file??? There may be another functions in the file and don't need to render other function.

Upvotes: 3

Views: 2995

Answers (3)

Ghermans41
Ghermans41

Reputation: 51

include a page lets say the function is GetPage and the variable is ID

<?php
require('page.php');

$id = ($_GET['id']);

if($id != '') {
  getpage($id);
}
?>

now when you make the function

<?php
function getpage($id){
if ($id = ''){
//// Do something
}
else {
}
}
?>

Upvotes: 0

user2632918
user2632918

Reputation:

In PHP it's not available to get only a little part of a file.

Maybe this is a ability to use only little parts of a file:

I have a class that calls "utilities". This I am using in my projects.

In my index.php

include("class.utilities.php")
$utilities = new utilities();

The file class.utilities.php

class utilities {
    function __construct() {

    }
    public function thisIsTheFunction($a,$b)
    {
        $c = $a + $b;
        return $c;
    }
}

And then i can use the function

echo $utilities->thisIsTheFunction(3,4);

Upvotes: 0

Huey
Huey

Reputation: 5220

The short answer is: no, you can't.

The long answers is: yes, if you use OOP.

Split your functions into different files. Say you are making a game with a hero:

Walk.php

function walk($distance,speed){
   //walk code
}

Die.php

function die(){
    //game over
}

Hero.php

include 'Walk.php';
include 'Die.php';

class Hero(){
    //hero that can walk & can die
}

You may have other functions like makeWorld() that hero.php doesn't need, so you don't need to include it. This question has been asked a few times before: here & here.

One of the possible methods outlined before is through autoloading, which basically saves you from having to write a long list of includes at the top of each file.

Upvotes: 2

Related Questions