Reputation: 4616
Is it possible to do something similar to this:
class Class1
{
public function __construct($param1) {
# code ...
}
public function method1() {
# code ...
echo 'works';
}
}
$class1 = new Class1('foo');
function function1() {
$class1->method1();
}
function1();
Or do I need to pass the instance of the class to the function ?
Thank you.
Upvotes: 0
Views: 119
Reputation: 2851
You must pass the instance to the function, or use GLOBALS :).
1) Instance - best solution
function function1(Class1 $class) {
$class->method1();
}
2) Globals - http://php.net/manual/en/reserved.variables.globals.php - But You must be careful, Globals, are very hard to follow and test your code. Best method is just to pass it as argument.
function function1() {
global $class1;
$class1->method1();
}
PS. You should try to avoid mixing object - function programming. If You decide to use object programming, try to implement everything as an object. It is easier to maintance, read and update. Mixing objects and function is good, only if You are 'rewriting' old system to object, and not everything can be done at once.
PS2. Objects should always implement real objects, or abstraction objects (router, database, table, user). In that case, when Your function needs object, passing it as a paremeter is what You need - in reality this function need this object. So there is no shame in passing it, rather proudness ;).
Best regards, hope it helps.
Upvotes: 1