tags:

views:

38

answers:

2

How can I access an extended Class function from an already created object?

(A) - This works, by not creating an object:

$UserType = 'User_Vote';
$vote = User::getVote($UserType)->getVoteQuery();

(B) - Trying the same idea from an already created object (this is what I want to do) returns the error: unexpected T_PAAMAYIM_NEKUDOTAYIM (unexpected '::')

$UserType = 'User_Vote';
$object = new User();
$vote = $object::getVote($UserType)->getVoteQuery();

(C) - But this works:

$UserType = 'User_Vote';
$object = new User();
$objectUserType = $object->getVote($UserType);
$finalObject = $objectUserType->getVoteQuery();

Why doesn't block (B) above with the double '::' work? It seems identical to block (A) except that the object is already created. Do I have to call each function separately as in block (C) to get around this?

+3  A: 

:: is for accessing static class methods or properties. The keyword being class, not object.
-> is for accessing object methods or properties. It doesn't work on classes.

The two are not interchangeable.

deceze
This explains it. Thanks
JMC
@JMC BTW, decide beforehand whether your methods should be called *statically* (as class methods) or as object methods and stick to that decision. Don't call them both ways throughout your code, or it will eventually break when you start to use class/object context specific keywords like `self` or `$this`.
deceze
@deceze: Thanks for the extra advice and providing a solid foundation. I'm going to read more into it before making a decision. The current code calls a static class method from an object returning 'self::'. Is that the type of intermixing that leads to issues?
JMC
@JMC If you're using `self` or `$this` in a method, that pretty much decides how the function can possibly be called. Do read up on different design patterns though, objects and classes have different use cases and are, again, not usually interchangeable.
deceze
+1  A: 

You can still chain methods in PHP 5 using the -> accessor. E.g.

$vote = $object->getVote($UserType)->getVoteQuery();

You should only use the Paamayim Nekudotayim, or :: when accessing static methods and properties in a class context, not object context.

Aether