Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Namespace and Include() with classes

Tags:

namespaces

php

there is a project which I need to extend. All classes are in seperate files, I need to extend some of the classes without rewriting existing code in other files. My idea was to use namespaces but I fail. Here is an example:

I've renamed the original A.php class file to A_Original.php:

class A
{

    public function hello()
    {
        echo "hello world from Class A\n";
    }

}

Then created a new A.php:

namespace AOriginal {

    include 'A_Original.php';
}


namespace {

class A
{

    public function hello()
    {
        echo "hello world from Class A Extended\n";
    }

}

}

This fails because on including the original A_Original.php file the class is dumped to the global scope (thus ignoring the namespace command). I can not modify the existing code inthe A_Original.php file, but renaming is ok.

The other project files (whic I cannot modify) use a require "A.php".

How to accomplish this?

like image 718
cydo Avatar asked Sep 11 '09 09:09

cydo


People also ask

What is the best approach for working with classes and namespaces in PHP?

To address this problem, namespaces were introduced in PHP as of PHP 5.3. The best way to understand namespaces is by analogy to the directory structure concept in a filesystem. The directory which is used to group related files serves the purpose of a namespace.

What is class namespace PHP?

A namespace is a hierarchically labeled code block holding a regular PHP code. A namespace can contain valid PHP code. Namespace affects following types of code: classes (including abstracts and traits), interfaces, functions, and constants. Namespaces are declared using the namespace keyword.

Can I use two namespace in PHP?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

What is the purpose of namespace in PHP?

In the PHP world, namespaces are designed to solve two problems that authors of libraries and applications encounter when creating re-usable code elements such as classes or functions: Name collisions between code you create, and internal PHP classes/functions/constants or third-party classes/functions/constants.


1 Answers

You can extend a class without modifying its existing behaviour:

class A {
  public function foo(){

  }
}

class MySubClassOfA extends A {
  public function bar(){

  }
}

You can add your own methods to MySubClassOfA, i.e. bar(). You can call the foo method on MySubClassOfA and it's behaviour is the same, unless you define a method called foo in MySubClassOfA.

like image 79
David Snabel-Caunt Avatar answered Nov 11 '22 15:11

David Snabel-Caunt