Brad
Brad

Reputation: 121

using includes in overall php rather then each function

i am very new to php, i am used to writing .net, and i am finding the includes hard to understand and was hoping someone could help me understand how to correctly use an include once in a file, rather than inside each function..

take the following as an example

<?php
include 'test.php';

function test($a)
{
 echo $value_from_test_php;
}
?>

the above code does not seem to work... however the below does

<?php

function test($a)
{
 include 'test.php'

echo $value_from_test_php;
}
?>

i am having a hard time figuring out how to make an include work for all functions inside a file, rather then including it inside each function, any advice is greatly appreciated!

Upvotes: 0

Views: 76

Answers (4)

kirugan
kirugan

Reputation: 2614

First example is not working because you use variable from global scope, if you want to use it then replace $value_from_test_php to $GLOBALS['my_var_name']

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157434

It's the scope of variable which is troubling you rather than includes, in PHP generally includes are used where there's a common page/markup to be included on each page, such as footer, header, etc

There are 4 types

  • include
  • include_once
  • require
  • require_once

The only difference is include will throw you an error if something goes wrong and will continue to execute the script where require will halt the further execution

You'll get everything here on includes - PHP Documentation

Upvotes: 1

Mark Parnell
Mark Parnell

Reputation: 9200

Your issue is not related to includes, but rather variable scope. By default a variable defined outside a function is not available within the function.

It's difficult to suggest the best solution without knowing exactly what it is you're trying to do, but the documentation (linked above) should get you started.

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137557

It all depends what is inside the file that you are include-ing! I would never, ever, suggest using include inside a function (or loop, or pretty much anything with brackets). Remember, the contents of the file being included are literally just "plopped in" place, right where the include statement is. So whatever scope (global, class, function, etc.) you're in when you include, is the scope that its contents will be declared in.

Put full class and function definitions in files, and include them at the top of the files where they are going to be used.

Upvotes: 0

Related Questions