Jump to content

Preventing main file functions from being global


Recommended Posts

How can I add a function to my main PHP file, yet not let it be available withing a class?  For instance, prevent baseFunction() from being available within foo.

<?php
class foo{
    public function bar()
    {
        echo(baseFunction()); //Global
        echo($baseVariable);  //Not global
    }
}

function baseFunction()  {return 'baseFunction';}
$baseVariable='baseVariable';

$foo=new foo();
$foo->bar();
Link to comment
Share on other sites

What exactly are you trying to achieve?

 

The only way to get a truly local function is to use a closure (anonymous function):

<?php

class Foo
{
    public function bar()
    {
        // cannot be called here
        $baseFunction();
    }
}



// closure
$baseFunction = function () { echo 'Closure'; };

// can be called here
$baseFunction();

$foo = new Foo();
$foo->bar();

Or you could use namespaces. This doesn't actually hide the function, but it makes it harder to access it.

Edited by Jacques1
Link to comment
Share on other sites

If the project is mostly object-oriented, consider moving the logic from the main script into a separate class. This will immediately solve the scoping issues and is generally cleaner.

 

Or use closures as explained above. But I feel this is more like a hack.

Link to comment
Share on other sites

I'd avoid the closures: they come with increased memory usage that does not get cleaned up until you use hundreds or thousands of closures. By design, which I still don't understand but is intentional.

 

If you want non-global functions, use namespaces or utility classes.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.