Hi, I'm working on a simpla CMS. And I'd like to create a public function that calls up all the nessecery classes and functions for the theme to run correctly. And not sure if it is possible to create something like the following.

function CMS_head() {

    $class1 = new class1();
    $class2 = new class2();
    $class2 = new class3();

    $class1->func1();
    $class2->func2();
    $class3->func3();

}

So they don't need to call each class and function one by one.

Recommended Answers

Functions have local scope by default for values declared within them, so add the following:

global $class1;
global $class2;
global $class3;    

Before you create your objects. This will give them global scope, so if you need to access them outside of your function, you can. If you don't need …

Jump to Post

Precisely. That will allow you to access your objects anywhere within your script. If you don't need to access your objects outside of the function however, there's no need to make the variables global. If you're finished with your objects by the end of the function, you won't need them …

Jump to Post

All 5 Replies

Functions have local scope by default for values declared within them, so add the following:

global $class1;
global $class2;
global $class3;    

Before you create your objects. This will give them global scope, so if you need to access them outside of your function, you can. If you don't need to access the objects outside of your function though, what you've written would be fine.

I see, so it would be something likes this?

function CMS_head() {

    global $class1;
    global $class2;
    global $class3;

    $class1 = new class1();
    $class2 = new class2();
    $class2 = new class3();

    $class1->func1();
    $class2->func2();
    $class3->func3();

}

Precisely. That will allow you to access your objects anywhere within your script. If you don't need to access your objects outside of the function however, there's no need to make the variables global. If you're finished with your objects by the end of the function, you won't need them to have global scope.

$class1->func1();

If you called that outside of your function without using global, you would get an error.

http://php.net/manual/en/language.variables.scope.php

No problem :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.