tags:

views:

112

answers:

5

We all know the infamous "cannot redeclare class" error. Is there any method to overcome this and actually declare a new class with the same name, or is this impossible in PHP 5?

+6  A: 

There may be a way using some obscure extension, but in basic standard PHP, as far as I know, no.

You can, however, always extend an existing class and - maybe, depending on your scenario - "smuggle" an instance of that extended class into the application you're working on.

Pekka
+1  A: 

AFAIK, redeclaring exiting functions or classes is not possible in PHP.

If you could tell, what you are trying to do, maybe there's another solution ...

Techpriester
+3  A: 

As Pekka and Techpriester both pointed out: no, you cannot. However, if you're using PHP >= 5.3, then you can use namespaces and the "use" construct to effectively "redeclare" the class. Here's an example:

// MyClass.php
class MyClass {
  const MY_CONST = 1;
}
// MyNamespaceMyClass.php namespace Mynamespace; class MyClass { const MY_CONST = 2; }
// example.php require_once 'MyClass.php'; require_once 'MyNamespaceMyClass.php';
use Mynamespace\MyClass as MyClass;
echo MyClass::MY_CONST; // outputs 2

Thus, you've got your desired result, as MyClass now refers to your namespaced class.

jpfuentes2
+1 nice workaround for those situations where there is no other way (3rd party software, etc.)
Pekka
+1  A: 
elias
A: 

Basically you cannot redeclare a class. But if you really want to, you can. :) Everything is possible. Need a class, that changes it's structure dynamically? You can use magic method __call and pattern State.

class Example
{
  var $state;

  public function setImplementation($state)
  {
    $this->state = $state;
  }

  public function __call($method, $args)
  {
    if (method_exists($this->state, $method))
       return $this->state->$method($args);
    else
      // error
  }

}

There is also a PHP toolkit to play with classes dynamically: http://php.net/manual/en/book.runkit.php

I know that redeclaring class and its methods is possible in Ruby (and I would consider it as a mistake in a language design).

topright