Search code examples
phpencapsulation

PHP encapsulation without class?


Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:

//Include the file containing the class which contains the variable or function
include('SomePage.php');

//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();

//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;

My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?


Solution

  • To use class methods and variables without instantiating, they must be declared static:

    class My_Class
    { 
        public static $var = 123;
    
        public static function getVar() {
         return self::var;
        }
    }
    
    
    // Call as:
    My_Class::getVar();
    
    // or access the variable directly:
    My_Class::$var;
    

    With PHP 5.3, you can also use namespaces

    namespace YourNamespace;
    
    function yourFunction() {
      // do something...
    }
    
    
    // While in the same namespace, call as 
    yourFunction();
    
    // From a different namespace, call as
    YourNamespace\yourFunction();