Jump to content

class and inline method


tdpaxton

Recommended Posts

I'm having some trouble instantiating a class and then calling an inline method.

 

<?php
    class SomeClass
    {
        public function activate($init = false)
        {
            return $init;
        }
    }

    if (new SomeClass().activate(true) == true) echo "It works!";
?>

 

...gives me the error...

 

Fatal error: Call to undefined function activate() in C:\wamp\www\index.php on line 10

 

Any suggestions?  Thanks!

Link to comment
https://forums.phpfreaks.com/topic/103593-class-and-inline-method/
Share on other sites

This is PHP, not Java  ;D

 

To access objects properties and methods you use the -> operator. The dot . operator is used to concatenate values.

 

try:

if (new SomeClass()->activate(true) == true) echo "It works!";

 

Can't remember if you can call a method at the same time you instatiate an object though, might give an error.

 

You can also call the function statically without instatiting the object with the :: operator, as in:

 

if (SomeClass::activate(true) == true) echo "It works!";

Oops, my bad!  I deal with about 4 different languages on a regular basis, so I guess its easy to get confused.

 

I tried...

 

if (new SomeClass()->activate(true) == true) echo "It works!";

 

But I get the error...

 

Parse error: syntax error, unexpected T_OBJECT_OPERATOR in C:\wamp\www\index.php on line 10

 

Firstly, is it possible to call a method on a newly instantiated object?  I realize that I could create the object and then call the method, but I was looking for a cleaner solution.  Thanks!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.