kazinix
kazinix

Reputation: 30123

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?

Upvotes: 1

Views: 787

Answers (3)

proseosoc
proseosoc

Reputation: 1354

This is a way to encapsulate without Class

<?php

(function (){

$xyz = 'XYZ';

})();

echo $xyz; // warning: undefined

Encapsulation Alternative

With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.

Example

<?php

define('APP', 'woi49f25gtx');

(function () {

    $pre = 'functions__math__'; // "functions" is main category, "math" is sub.

    $GLOBALS[APP][$pre . 'allowedNumbers'] = [3,5,6];

    $GLOBALS[APP][$pre . 'square'] = function ($num) {
        return $num * $num;
    };

    $GLOBALS[APP][$pre . 'myMathFunction'] = function ($num) use ($pre) {
        if(in_array($num,$GLOBALS[APP][$pre . 'allowedNumbers'])) return 'not allowed';
        return $GLOBALS[APP][$pre . 'square']($num);
    };

})();

echo $GLOBALS[APP]['functions__math__myMathFunction'](4);

Upvotes: 0

sanmai
sanmai

Reputation: 30911

PHP Namespaces were made to archive the exact same goal:

<?php // foo.php
namespace Foo;
function bar() {}
class baz {
    static $qux;
}
?>

When using call namespaced functions like this:

<?php //bar.php
include 'foo.php';
Foo\bar();
Foo\baz::$qux = 1;
?>

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270677

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();

Upvotes: 3

Related Questions