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
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!";

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

I thought it might give an error, and it did... so I guess it's not possible.

 

You can call it statically if it's just a simple generic true/false function, it's the closest to what you wanted. Or simply instatiate it properly beforehand.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.