سؤال


Anyone know how to redeclare function?
For example:

class Name{}
//Code here
class Name{}

And the output is: Cannot redeclare class
So I tried to name the class as a variable:

$foo = 'name';
class $foo{}

//Code

class $foo{}

Edit: I have a DataBase table and I am reading data from the table user 'while()' loop.
I have a class that uses the table and echo some information. That is the reason.

And it's still not working...
Any suggestions?

هل كانت مفيدة؟

المحلول 2

Use PHP NameSpace

namespace A {

    class Name {

        function __toString() {
            return __METHOD__;
        }
    }
}

namespace B {

    class Name {
        function __toString() {
            return __METHOD__;
        }
    }
}

namespace C {

    echo new \A\Name ,PHP_EOL;
    echo new \B\Name ,PHP_EOL;
}

Output

A\Name::__toString
B\Name::__toString

نصائح أخرى

If you want to have several classes with the same name, then you should be using namespaces.

Nope. PHP simply doesn't support runtime modification of an existing class

Why would you want to re-declare a class? when you ca reference to it at any point?

I think what you're looking for is to create a new instance of a class:

$foo = 'name';
$obj1 = new $foo();

//Code

$obj2 = new $foo();

You shouldn't have 2 or more classes with the same name. This is not working. How should the interpreter know which class is the correct class?

Change the name of the second class and extend them if you need it.

Edit: Use Namespaces of you need the same classname or if you have an existing class.

If you need two instances of a class you can just initialise it twice as two different varialbes;

class Foo{}

$foo1 = new Foo;
$foo2 = new Foo;

Use PHP namespaces to declare classes with the same name but different purposes.

First of all: Do not do this.

That said, if you really need to "refedine" a class, you can use a wrapper class to do so

<?php

class foo { //Original definition here };

class bar {
  var $baseobj;

   function bar($some, $args) {
     $this->baseobj=new $which($some, $args);
   }

   function someMethod() {
      return $this->baseobj->someMthod();
   }

   //...
} 

class baz {

   function someMethod() {
      return "This is the result";
   }

   //...
} 

$obj=new bar($this, $that);
//$obj is now a wrapped foo object
echo $obj->someMethod(); //Will call into foo

$obj->baseobj=new baz($this, $that);
//$obj is now a wrapped baz object
echo $obj->someMethod(); //Will call into baz
?>

Again: Do not do this without a very, very good reason!

Disclaimer: This implementation is more than crude, it is only ment to transport the idea.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top