Namespace assistance

Hi all, i have been a fan of sitepoint for a while now.

I have come to a hard place and require a little assistance.

I have the following Class (file : headScript.php)

    class headScript
    public function connection()
    $dbh = new PDO("mysql:host=localhost;dbname=xxx", 'xxx', 'xxx'); // Dev
    return $dbh;
    catch(PDOException $e)
    echo "Error :- " . $e->getMessage();
    public function headLoad()
    $cxn = $this->connection()->prepare("SELECT scriptCode FROM head_scripts WHERE active != '0'");
    while($row = $cxn->fetch())
    print "<script>";
    print $row['scriptCode'];
    print "</script>";

I’d like to remove the connection function and put this in its own file, then using namespace to pull this in. That way i have one file which can be called via namespace and i can use this function.

Am I thinking this is possible when it is not?

I have tried a few things but cant seem to get it to work.

Can anyone offer assistance?

Don’t see why you need namespacing…

logic_earth thank you for posting back.

My reason is so that i have the db connection accessable for where i need it. I do not wish to keep typing the connection info.

Hope that makes sense?

You don’t need namespacing for that.
Just throw the connection into a file then include it. Then for methods/functions that need it pass it as a parameter/argument.

Thank you. had thought of that.

What is the use/need of namespacing then, or have i missed the point on them?

Namespacing is for much larger projects…which have multiples of interconnecting libraries.

That is one purpose, another is when you need to separate components that are likely to have similar names for different purposes. Example, I might have an Output file for an Email form and an object that stores Email related data and handles sending emails. I could name them OutputEmail and ObjectEmail (yes, you could have an output function in your email object, but I like to separate content from business logic/data access – my .NET side is showing again), or I could use namespaces and have \Output\Email and \Object\Email. Namespaces are a way to organize your classes and libraries.

@Wbsite Creation, you likely want to create a Database Class. One that can help assist your database querying, connections, fetching results, etc. You would typically write this in a separate file and use require_once to include the class and then utilize the class where needed.