tags:

views:

369

answers:

2

Suppose I have a php file along these lines:

<?php
function abc() {  }

$foo = 'bar';

class SomeClass {  }
?>

Is there anything special I have to do to use abc() and $foo inside SomeClass? I'm thinking along the lines of using global in a function to access variables defined outside the function.

(I'm new to OOP in PHP)

+1  A: 

functions are defined at a global level ; so, you don't need to do anything to use them from a method of your class.

For more informations, see the function page in the manual, which states (quoting) :

All functions and classes in PHP have the global scope - they can be called outside a function even if they were defined inside and vice versa.


For your $foo variable, on the other hand, you have to use the global keyword inside each method/function in which you want to access it.

For more informations, don't hesitate to read the page about Variable scope, which should bring you interesting informations ;-)


Edit after the comment :

Each method/function regardless of it being defined within a class or not?

If a "function" is defined inside a class, it's not called a "function" anymore, even if it is still the function that is used : it is called a "method"

Methods can be used statically :

MyClass::myMethod();

Or Dynamically :

$obj = new MyClass();
$obj->myMethod();

Depending on whether they were defined as static or not.


As a sidenote : if you are new to OOP in PHP, you should definitly invest some time to read the Classes and Objects (PHP 5) section of the manual : it will explain much.

Pascal MARTIN
Each method/function regardless of it being defined within a class or not?
Shadow
@Shadow : I've edited my answer to provide a bit more informations -- hope this helps!
Pascal MARTIN
A: 

functions outside any class are global an can be called from anywhere. The same with variables.. just remember to use the global for the variables...

e.g

<?php
function abc() {  }

$foo = 'bar';

class SomeClass {  
 public function tada(){
     global $foo;

     abc();
     echo 'foo and '.$foo;
 }
}
?>
PHP_Jedi