PHP "Object" class
I'd like to create a class called "Object" to be able to implement "toString()", "equal()"... The problem is that the "object" keyword is already taken and I wonder what would be the best implementation.
The first option that comes up to my head is by using namespaces so I don't have any concurrency between php's "object" class and mine. The problem is that if I want to use the two "Object" class, I'll need to r开发者_Go百科ename one of them in my code later.
namespace System
{
class Object
{
}
}
...
use System\Object as Object1;
use object as Object2;
An other option would be to call it differently. If you think its the best option, how would you call it?
class ObjectD
{
}
Do you have any better options?
You could use a synonym, such as Entity
or Item
.
Oh and by the way, the main/base/root object class is called stdClass
.
Edit: I think it's absolutely impossible to use 'object' anywhere by itself.
Consider the following:
$test = new object();
$test = (object) array();
Running the above code, how would PHP know which is which?
Edit 2: Also, if I understand you correctly, you want to create your own object hierarchy. In such a case, you should name the object according to what you're doing. For example, in Joomla, there is JObject.
If I had to share my experience, you should always have a valid prefix to your global naming stuff. I've realized this only recently with a little pet project of mine.
Edit 3: Just tried it:
use System\Object as Object1;
use object as Object2;
class object {
public $test='aaa';
}
$a=new object();
$b=(object)array('aaa'=>'test');
echo '<pre>';
print_r($a);
print_r($b);
Printed:
object Object
(
[test] => aaa
)
stdClass Object
(
[aaa] => test
)
Edit 4: Interestingly, this even works without namespacing.
Using reserved words always might create problem. Esspecially if later on some other programmer would work on your project, you might put the programmer in sleepless nights.
I would go with;
class ObjectD
{
}
This might not be exactly what you want since you want to use the name object but at the very least, you will write less codes which is a good thing.
I also would like to add, if you will use it in big project, be sure you will spend lots of time in debugging and eventually you will want to change your code.
精彩评论