JMC
JMC

Reputation: 1697

Help Accessing an Extended Class Function - PHP OOP

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?

Upvotes: 0

Views: 458

Answers (2)

Aether
Aether

Reputation: 364

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.

Upvotes: 1

deceze
deceze

Reputation: 522101

:: 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.

Upvotes: 3

Related Questions