0

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.

2
  • Nope Don't do it.do this instead function function1() { $class1 = new Class1('foo'); $class1->method1(); } Commented Jan 17, 2015 at 16:21
  • @Shan The reason I don't do this is that the parameter I send to the class (a config array in this case) is not accessible from the function. Commented Jan 17, 2015 at 16:22

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, it's what I thaught.
No problem. It is a good habit, to always pass variables / attributes / objects as a function arguments. It makes the code, clear, dependencies are clear, and it is very easy to test the code on each level.
In my actual project, I only have 4 functions, which are quite small, but not linked in any way (add_log, add_zero, connection_db and format_exception), and I don't believe it makes it easier to put them all in one class and make them static.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.