How can I avoid two Class with same name? - php

In my php file i am doing it this way
pagecontroller.php
include_once(RUDRA."/controller/AbstractTemplateController.php");
if (file_exists(get_include_path() . CONTROLLER_PATH . "/TemplateController.php" )) {
include_once (CONTROLLER_PATH . "/TemplateController.php");
} else {
include_once (RUDRA . "/controller/TemplateController.php");
}
in TemplateController.php a class named 'TemplateController extends AbstractTemplateController' is defined, if a developer has already defined a class TemplateController which also extends AbstractTemplateController then it will use that otherwise it will fallback to default definition.
then in other files i will simply use something like this
include_once("pagecontroller.php")
$c = new TemplateController();
is there any better way to do this?
since I am including two files AbstractTemplateController.php & TemplateController.php in both cases, I cpuld have written both class definitions in same file which would have saved one include(if there is no custom TemplateController.php)?
I tried writing AbstractTemplateController & TemplateController in one single file but if then developer has defined his own TemplateController it creates two classes with same name situation.
pupose is to have atleast one definition to be there, if customDefinition does not exists then only use default one. and this code is to be abstract.
in the beginning if CustomClass exists (in a specific folder) then that the definition to be used, else use default one (which is nothing but simply extends AbstractOne)
CONTROLLER_PATH . "/TemplateController.php"
class TemplateController extends AbstractTemplateController {
/* over-ridden method of AbstractTemplateController
*/
public function invoke($abc,$def){
echo $abc . " " .$def;
}
}
RUDRA . "/controller/TemplateController.php"
class TemplateController extends AbstractTemplateController {
// nothing at all this is simply to make sure TemplateController class is available
// for others to use.
}

Use namespaces and convention.
E.g. you could check if there's a TemplateController-class present that extends the AbstractTemplateController that's different from your namespace (As your implementation will be specific for your namespace), if there isn't ; fall back to your implementation of the TemplateController.
http://php.net/manual/en/language.namespaces.php

php provides a function for not letting you load/write a class more then once.
bool class_exists ( string $class_name );
example is :
<?php
function __autoload($class)
{
include($crigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}lass . '.php');
// Check to see whether the include declared the class
if (!class_exists($class, false)) {
trigger_error("Unable to load class: $class", E_USER_WARNING);
}
}
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
in above example autoload is used, you could do it without autoload this way :
<?php
// Check that the class exists before trying to use it
if (class_exists('MyClass')) {
$myclass = new MyClass();
}
?>
still i am saying you better get habit of using namespaces. they are awesome and work every where.

Related

add more methods to class using include_once [duplicate]

I want to make a PHP class, lets say Myclass.php. Now inside that class I want to define just the class itself and some instance variables. But all the methods must come from a Myclass_methods.php file. Can I just include that file into the class body?
I have good reasons why I want to seperate this. In short, I'll have a backend in which I can change the business logic of a class, while all other things must remain untouched. The system maintains all the ORM and other stuff for me.
But if this is a bad idea, it might be better to re-generate the whole class file after editing the business logic (so, the user-defined methods in this case).
Performance question: If during one request Myclass.php is included just once, actually that Myclass_methods.php should also be included just once. Might be wrong. Experts?
No. You cannot include files in the class body.
In a file defining a class, you may only include files in a method body or outside the class body.
From your description I take you want this:
<?php // MyClass.php
class MyClass
{
protected $_prop;
include 'myclass-methods.php';
}
<?php // myclass-methods.php
public function myMethod()
{
$this->$_prop = 1;
}
Running this code will result in
Parse error: syntax error, unexpected T_INCLUDE, expecting T_FUNCTION
What is possible though is this
<?php // MyClass.php
class MyClass
{
protected $_prop;
public function __construct() // or any other method
{
include 'some-functions.php';
foo($b); // echoes 'a';
}
}
<?php // some-functions.php
$b = 'a';
function foo($str)
{
echo $str;
}
Doing it this way, will import the contents of the include file into the method scope, not the class scope. You may include functions and variables in the include file, but not methods. You could but should not put entire scripts into it as well and change what the method does, e.g.
<?php // MyClass.php
// ...
public function __construct($someCondition)
{
// No No Code here
include ($someCondition === 'whatever') ? 'whatever.php' : 'default.php';
}
// ...
<?php // whatever.php
echo 'whatever';
<?php // default.php
echo 'foo';
However, patching the class this way to exhibit different behavior is not how you should do it in OOP. It's just plain wrong and should make your eyes bleed.
Since you want to dynamically change behavior, extending the class is also not a good option (see below why). What you really will want to do is write an interface and make your class use objects implementing this interface, thus making sure the appropriate methods are available. This is called a Strategy Pattern and works like this:
<?php // Meowing.php
interface Meowing
{
public function meow();
}
Now you got the contract that all Meowing Behaviors must obey, namely having a meow method. Next define a Meowing Behavior:
<?php // RegularMeow.php
class RegularMeow implements Meowing
{
public function meow()
{
return 'meow';
}
}
Now to use it, use:
<?php // Cat.php
class Cat
{
protected $_meowing;
public function setMeowing(Meowing $meowing)
{
$this->_meowing = $meowing;
}
public function meow()
{
$this->_meowing->meow()
}
}
By adding the Meowing TypeHint to setMeowing, you make sure that the passed param implements the Meowing interface. Let's define another Meowing Behavior:
<?php // LolkatMeow.php
class LolkatMeow implements Meowing
{
public function meow()
{
return 'lolz xD';
}
}
Now, you can easily interchange behaviors like this:
<?php
require_once 'Meowing.php';
require_once 'RegularMeow.php';
require_once 'LolkatMeow.php';
require_once 'Cat.php';
$cat = new Cat;
$cat->setMeowing(new RegularMeow);
echo $cat->meow; // outputs 'meow';
// now to change the behavior
$cat->setMeowing(new LolkatMeow);
echo $cat->meow; // outputs 'lolz xD';
While you also could have solved the above with inheritance by defining an abstract BaseCat and meow method and then deriving concrete RegularCat and Lolkat classes from that, you have to consider what you want to achieve. If your cats will never change the way they meow, go ahead and use inheritance, but if your RegularCat and Lolkat is supposed to be able to do arbitrary meows, then use the Strategy pattern.
For more design patterns in PHP, check these resources:
http://www.php.net/manual/en/language.oop5.patterns.php
http://www.ibm.com/developerworks/library/os-php-designptrns/
http://www.fluffycat.com/PHP-Design-Patterns/
http://sourcemaking.com/design_patterns
Might it not be an idea to create the core class with the relevant base functionality and then extend this with the required methods - it seems like a more logical approach.
I'll start by saying I'm not too clear why this problem is not best solved using a base class containing the methods, subclasses containing the data, and dynamic class loading. I'll assume you have a good reason.
Once your provider supports PHP 5.4 you can do what you want using traits.
Code File:
if ($pet === 'dog') include 'dog.php';
elseif ($pet === 'cat') include 'cat.php';
else die('Unknown pet');
class Pet {
use PetSounds;
}
$myPet = new Pet();
$myPet->speak();
File cat.php
trait PetSounds {
function speak() { echo 'meow'; }
}
File dog.php
trait PetSounds {
function speak() { echo 'woof'; }
}
You could make this even cleaner by naming both include files the same, putting them in different subdirectories, and using set_include_path() or defining an __autoload() function to select between them. Like I said though, this same problem could be solved better using inheritance. If you have a multiple-inheritance type problem though, if for instance you have four kinds of pets with five kinds of colors with three hair types and you need a different combination of methods for each of the 60 different classes, this is the right solution.
5.4 is currently just a Release Candidate (as of 2/24/2012) and even once released most hosts will not support it for many months - mine took 18 months after 5.3 was released before they would support it. Until then you must write entirely separate and complete class files. You can however format your classes with an eventual change to traits in mind.
Right now you can partially get what you want using magic methods and have an easy upgrade to traits when they are available.
Code File:
if ($pet === 'dog') include 'dog.php';
elseif ($pet === 'cat') include 'cat.php';
else die('Unknown pet');
class Pet {
public function __call($name, array $arguments)
{
array_unshift($arguments, $this);
return call_user_func_array("TraitFunc_$name", $arguments);
}
}
$myPet = new Pet();
$myPet->speak();
File cat.php
function TraitFunc_speak(Pet $that) { echo 'meow'; }
File dog.php
function TraitFunc_speak(Pet $that) { echo 'woof'; }
You are limited however in that your functions can not access private and protected class properties and methods and you can not use this method to provide magic methods such as __get(). Traits will solve both of those limitations.
What about using traits for this? Would that be an acceptable option? This is something I am currently experimenting with and it seems to work quite while.
A simplified version of what I am doing is basically like this. I have an application with shared core files and multiple projects. Within those projects i have modules. I want to have functions that are available for the entire project on a core level but only for that specific project.
My project controller
if(is_file(PROJECT_PATH.'/project_extensions.trait.php')){
// additional functions for this specific project
require_once(PROJECT_PATH.'/project_extensions.trait.php');
}else{
// no additional functions
trait Extensions{};
}
Class Project{
USE Extensions;
// default functions shared between all projects
function shared_stuff(){
}
}
Extensions file
trait Extensions{
// project-specific extensions
function this_project_only(){
echo 'Project Only';
}
}
Module file in the project
class MyModule extends Modules{ // modules extends projects in a different class not relevant here
function do_something(){
echo $this->project_only();
}
}
Since PHP5.4 release you can create dynamic objects like this: https://github.com/ptrofimov/jslikeobject
But this is scarcely the best practice.
Reviving an old question but this is a fairly simple solution. Do you need the common function calls to be exclusive to your class? If not, simply include your common function file(s) within the same scope as your class. You will need to create methods in your class but they will only need to call the common function. Here's a simple SOAP server example:
<?php
include 'post_function.php';
$server = new SoapServer( null, array('uri' => "http://localhost/") );
$server->setClass( 'postsoapclass' );
$server->handle();
class postsoapclass
{
public function animalNoise( $animal )
{
return get_animal_noise($animal);
}
}
?>
post_function.php
<?php
function get_animal_noise($animal)
{
if(strtolower(trim($animal)) == 'pig')
{
return 'Oink';
}
else
{
return 'This animal is mute';
}
}
?>
I have had to do what you are describing in cases where I maintain a free version and a premium version of the same software. Because, as #Gordon noted, you cannot do exactly this:
class SomeClass {
premium_file = "premium.php";
if (file_exists($premium_file)) {
require($premium_file);
}
Instead I do this:
premium_file = "premium.php";
if (file_exists($premium_file)) {
require($premium_file);
}
class SomeClass {
...
For functions you want to reference, create class methods in the main class, and call the included file's method, passing the $this pointer as a parameter. So that I can tell at a glance where functions are, I will prefix the name of the included functions as shown below:
class SomeClass {
...
// Premium functions
public function showlist() {
premium_showlist($this);
}
You can include or require before declaring your class like below:
require 'path-to-file';
class myClass{
function show($uid){
}
}
The answer is yes, for example:
Into class construct, pass to the function (that's into the included file) values as params:
$this->wpd = $this->wpdopt = 'something';
include_once('/common/functions_common.php');
$this->wpdb = wpquery($sql='', $mode='', $this->wpd);
Into the included functions_common.php file:
function wpquery($sql, $mode, $wdp)
{
if(!empty($wdp))
{ return true; } else { return false; }
}
Into class methods:
$sql = "UPDATE ..... SET ... WHERE LOWER(user_email) = . ...";
$this->wpdb = wpquery($sql,'update',$this->wpd);
OR
$retval_var = $this->wpdb = wpquery($sql,'update',$this->wpd);
OR even
$this->var = $this->wpdb = wpquery($sql,'update',$this->wpd);
Cheers to all the lovely and cool people
I came across this recently, and came up with a solution, that helped in my case. I wanted many functions in a class, but the class became bloated, so wanted to separate out the class functions into groups for readability. It took a little time to accomplish, but since the functions of the class didn't rely (much) on $this, I removed "$this" from the class functions and created several helper files to include those functions. When $this was necessary, I could nevertheless move the function into a helper file, by passing $this to the function, adding public set/get functions where necessary. It's a hack, but it's sure to help someone
class myClass
{
var x;
function myClass()
{
$this->x = 0;
}
function myFunc1Group1()
{
$x = $this->x;
$x++;
$this->x = $x;
}
function myFunc2Group1(){}
function myFunc1Group2(){}
function myFunc2Group2(){}
}
can be worked around to
class myClass
{
var x;
function myClass()
{
$this->x = 0;
}
function doSomething()
{
// not called on $this but takes $this as a parameter
myFunc1Group1($this);
}
}
and helper function set 1
function myFunc1Group1($THIS_OBJECT)
{
$x = $THIS_OBJECT->getX();
$x++;
$THIS_OBJECT->setX($x);
}
function myFunc2Group1($THIS_OBJECT){}
and helper function set 2, etc.
Probably not the best route in all cases, but helped me out a lot. Basically the class functions were only to construct and delegate, and the calculations were put into helpers.

Laravel 5.1 - How to use Model in Global function file

I created a common.php for my all the global function. When I run my first function {{Common::test()}}
It's working fine But I can not use model in it.
namespace App\library;
{
class Common {
public static function test()
{
echo "Yes";
return "This comes from Common File";
}
public static function getCmsBlocks()
{
$model = Modelname::all();
if($model){
echo "asdad";
}else
{
echo "sadasd";
}
}
}
}
I don't get my output when I run {{Common::getCmsBlocks()}}
If your model is in different namespace than App\library you will need to prefix the model class name with its namespace, otherwise PHP will try to load App\library\Modelname which might not be what you need.
Replace
$model = Modelname::all();
with
$model = \Your\Model\Namespace\Modelname::all();
If you use your Modelname class in multiple place in declared namespace, you can import/alias that using use statement so that you can refer to that class by classname in your code:
namespace App\library;
use Your\Model\Namespace\Modelname;
{
class Common {
public static function getCmsBlocks()
{
$model = Modelname::all(); //this will work now
}
}
}
There is no way to define global use to bused by all namespaces in your file, as use always refers to the namespace being declared.
As above the answer is perfect but just a few addition if you don't want to include namespace everytime on at start of each file
Use this :
\App\ModelName::all();
\App\ModelName1::update(item);
\App\ModelName2::find(1);
give path like above and there will be no need to use namespace everytime .
Note: above is path to model which is inside App directory . So change accordingly if you are keeping them at separate place .

How does a php class determine which class to extend, given there are two class with the same name?

Given I have two User classes, one located in /model/User.php and the other located in /assets/User.php
Now I want to have a class which extend the User class from /model/User.php, yet it seems that php is always looking for the one located in /assets/User.php. Any idea how does php determines which class to extend from?
Use namespaces
user.php:
class User {
function someMethod(){}
}
myUser.php:
namespace My;
class User {
function someMethod(){}
}
And you can use it like this:
include 'user.php';
include 'myuser.php';
$user1 = new User();
$user2 = new \My\User();
You can use namespaces: PHP Manual
You should (if you use) setup appropriately your spl_autoload_register function (http://php.net/manual/en/function.spl-autoload-register.php) to be able autoload the objects in files with same name, bud the names of object can not be the same.
You can distinguish the objects by name and path in which the files are stored.
For instance, you require core class in your bootstrap.php and define autoloading function:
<?php // bootstrap.php
require_once Core.php;
spl_autoload_register(array('Core', 'auto_load'));
$myUserClass = new MyClasses_User() // the required files for the class are loaded because of auto_load, PHP determines the right classes due to naming conventions: DirName_ClassName
?>
<?php // Core.php
define('DIR_SEPARATOR', '/');
class Core {
// Autoloading
public static function auto_load($class, $dir_classes = 'classes')
{
$file = str_replace('_', DIR_SEPARATOR, $class); // replace _ by / for path to file
if ($path = find_file_based_on_class_name($dir_classes, $file))
{
// Load the class file
require $path;
}
}
?>
<?php
// classes/Model/User.php
class Model_User {
// define the class
}
?>
// classes/Assets/User.php
<?php
class Assets_User {
// define the class
}
?>
// classes/MyClasses/User.php
<?php
class MyClasses_User exdends Model_User {
// define the class
}
?>

How do you add abstract class library in the Codeigniter framework?

I have the following code in file called AbstractClass.php in the libraries folder
abstract class AbstractClass {
abstract protected doSomething ();
}
class ConcreteClass extends AbstractClass {
public function doSomething () {};
}
When I try to load the AbstractClass from controllers as follows:
$this->load->library('AbstractClass');
I get Unable to load the requested class: AbstractClass error.
What am I doing wrong? Should I just include the file rather than loading it?
Thanks
Well obviously you cannot load an abstract class directly as this goes against the point of an abstract class.
You can put an abstract class in a file along with another library, but that is a bit pointless and goes against the "one class one file" standard that CI (and all good standards) suggest.
You can include this file with an include() in your library files, or set up an __autoload() function to do it for you. Best place for an __autoload() is the bottom of config.php.
I use abstract classes with CodeIgniter libraries because I have common methods which I want all inherited classes to use which are meaningless on their own. I don't know if what I'm about to suggest is best practise. I suspect it's not, but I personally find it useful. Here's how I do it:
Create a new classes folder in the CodeIgniter application folder.
Add this folder to the path. (I usually do this in the controller.)
if (!strstr(get_include_path(), APPPATH . 'classes')) {
ini_set('include_path', get_include_path() . ':' . APPPATH . 'classes');
}
Create the abstract classes, or other classes, in the classes folder.
Create an extended CodeIgniter library:
require_once('an_abstract_class.php');
class concrete_library extends an_abstract_class {
Use the library as normal:
$this->load->library('concrete_library');
That should do the trick. I hope this is useful.
Ok. I know this is WAY late, but I'm sure many people are having questions about this.
This is actually a limitation of the core Loader class, as it attempts to instantiate each of the items defined by the first parameter. As we all know, Abstract Classes by their very definition are Abstract and CANNOT be instantiated. So how do we get around this?
But most importantly: How do we get around this while conforming to the CodeIgniter Standards?
Since I've only just started using CodeIgniter, I can't really say for certain how Core Extensions were handled in the past. However, in the most recent version, the CodeIgniter framework will allow you to extend and override its core classes by Prefixing the filename with your defined Subclass Prefix (in most cases "MY_") followed by the name of the file you plan on extending.
*/application/core/MY_Loader.php*
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader{
public function __construct(){
parent::__construct();
}
}
?>
Chances are good that if you know how to utilize Abstract Classes, you know what this does. Basically, this Class now inherits all properties and methods of the original CI_Loader class. The code snippet above is technically an exact duplicate of the original Loader Class, but the most important thing here is that now this class will take over all load methods rather than the original.
Now all we need to do is provide the loader class with the means to know if it's loading and instantiating a concrete class, or if it's simply including an abstract class.
There are two methods that handle the loading of any Libraries:
Method 1) public function library
Method 2) protected function _ci_load_class
Method 1 handles the processing of all parameters passed to it by iterating through itself if the first parameter is an array, makes sure the data provided is clean, and prevents any actions from being taken if certain criteria aren't met.
Method 2 handles the actual loading of the necessary assets, error handling, etc.
We can override the behavior of methods 1 and 2 by redefining them within our new MY_Loader Class. I've done this by creating almost exact replicas of the original methods, but with the addition of a 4th parameter that - when true - will prevent the Loader from instantiating the defined Library Class in the second method. I've also included an additional method public function abstract_library that will allow you to explicitly define the Library as Abstract in shorthand fashion.
The following is the MY_Loader.php class in its entirety. This will not affect any existing calls to the library method.
Hope this helps!
*/application/core/MY_Loader.php*
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Loader extends CI_Loader{
public function __construct(){
parent::__construct();
}
public function library($library = '', $params = NULL, $object_name = NULL, $is_abstract=false){
if(is_array($library)){
foreach ($library as $class){
$this->library($class, $params);
}
return;
}
if($library == '' OR isset($this->_base_classes[$library])){
return FALSE;
}
if(!is_null($params) && ! is_array($params)){
$params = NULL;
}
$this->_ci_load_class($library, $params, $object_name, $is_abstract);
}
public function abstract_library($library=''){
$this->library($library, NULL , NULL, true);
}
protected function _ci_load_class($class, $params = NULL, $object_name = NULL, $is_abstract=false)
{
$class = str_replace('.php', '', trim($class, '/'));
$subdir = '';
if(($last_slash = strrpos($class, '/')) !== FALSE){
$subdir = substr($class, 0, $last_slash + 1);
$class = substr($class, $last_slash + 1);
}
foreach(array(ucfirst($class), strtolower($class)) as $class){
$subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php';
if(file_exists($subclass)){
$baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php';
if (!file_exists($baseclass)){
log_message('error', "Unable to load the requested class: ".$class);
show_error("Unable to load the requested class: ".$class);
}
if(in_array($subclass, $this->_ci_loaded_files)){
if(!is_null($object_name)){
$CI =& get_instance();
if(!isset($CI->$object_name)){
return $is_abstract ? true : $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
}
}
$is_duplicate = TRUE;
log_message('debug', $class." class already loaded. Second attempt ignored.");
return;
}
include_once($baseclass);
include_once($subclass);
$this->_ci_loaded_files[] = $subclass;
return $is_abstract ? true : $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name);
}
$is_duplicate = FALSE;
foreach ($this->_ci_library_paths as $path){
$filepath = $path.'libraries/'.$subdir.$class.'.php';
if(!file_exists($filepath)){
continue;
}
if(in_array($filepath, $this->_ci_loaded_files)){
if(!is_null($object_name)){
$CI =& get_instance();
if(!isset($CI->$object_name)){
return $is_abstract ? true : $this->_ci_init_class($class, '', $params, $object_name);
}
}
$is_duplicate = TRUE;
log_message('debug', $class." class already loaded. Second attempt ignored.");
return;
}
include_once($filepath);
$this->_ci_loaded_files[] = $filepath;
return $is_abstract ? true : $this->_ci_init_class($class, '', $params, $object_name);
}
} // END FOREACH
if($subdir == ''){
$path = strtolower($class).'/'.$class;
return $this->_ci_load_class($path, $params, $is_abstract);
}
if($is_duplicate == FALSE){
log_message('error', "Unable to load the requested class: ".$class);
show_error("Unable to load the requested class: ".$class);
}
}
}
?>
Loading an abstract library:
<?php
$this->load->library("My_Abstract_Library", NULL, NULL, true);
/* -- OR -- */
$this->load->abstract_library("My_Abstract_Library");
?>
I haven't seen any examples around the web of Abstract classes with CI so I wanted to confirm that you can have an Abstract library. There are very good reasons which are fundamental to OOP as to why Abstract classes are useful. Fundamentally for me to ensure the child classes follow certain consistencies.
Let me know if you need an example, as you manually have to include the abstract class make sure you only do it once so you don't get issues with redeclaring classes.
Also don't forget if you have a static function or variable in the Abstract class you can still access it directly without having to load the class as in the below
AbstractClass::static_method_you_want_to_call();
I have found a simple way to use an abstract classes in Codeigniter. Just follow these steps. Go to libraries in system folder
Create an abstract class and dont link it with CI just name it with simple word without CI_
Create an another class name it with the same word as you give name to your file. As shown in code below
Extend that class with abstract class.
Then call abstract class function through your CI_class.
System -> libraries -> lib.php
abstract class B
{
public function lib1()
{
echo "This is library 1";
}
public function lib2()
{
echo "This is library 1";
}
}
class CI_lib extends B
{
public function libs(){
$this->lib1();
}
}
Then call that lib from Controller.

php5 and namespace?

I work a lot in PHP but I never really understand the namespace method in PHP. Can somebody help me here? I have read on php.net's website its not explained good enough, and I can't find examples on it.
I need to know how I can make code in sample version.
namespace: sample
class: sample_class_1
function: test_func_1
class: sample_class_2
function: test_func_2
function: test_func_3
Like this?
<?php
namespace sample
{
class Sample_class_1
{
public function test_func_1($text)
{
echo $text;
}
}
class Sample_class_2
{
public static function test_func_2()
{
$c = new Sample_class_1();
$c->test_func_1("func 2<br />");
}
public static function test_func_3()
{
$c = new Sample_class_1();
$c->test_func_1("func 3<br />");
}
}
}
// Now entering the root namespace...
// (You only need to do this if you've already used a different
// namespace in the same file)
namespace
{
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();
}
// Now entering yet another namespace
namespace sample2
{
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();
}
If you're in another file you don't need to call namespace { to enter the root namespace. So imagine the code below is another file "ns2.php" while the original code was in "ns1.php":
// Include the other file
include("ns1.php");
// No "namespace" directive was used, so we're in the root namespace.
// Directly addressing a class
$c = new sample\Sample_class_1();
$c->test_func_1("Hello world<br />");
// Directly addressing a class's static methods
sample\Sample_class_2::test_func_2();
// Importing a class into the current namespace
use sample\Sample_class_2;
sample\Sample_class_2::test_func_3();

Categories