drlobo
drlobo

Reputation: 2159

PHP how to have declare a class member?

Slightly confused with PHP because it does not declare object variable types. This is simplified code which does not work. I get why I get an error but not sure how in PHP I can specify that $pb is a PushBot object and so it has methods which can be used.

    class Bot 
{

     public $pb;

//Constructor
 function __construct(){
     require_once('../PushBots.class.php');
     // Application ID
     $appID = '';
     // Application Secret
     $appSecret = '';
     // Push The notification with parameters
     $this ->pb = new PushBots();
     $this ->pb->App($appID, $appSecret);

     }

//Method. The $this->pb->Push() does not work
 public function sendMessage(){
        $this->pb->Push();
     }

}

//Client calling the class

$bot = new Bot();
$bot->sendMessage();

The error I get is :

Parse error: syntax error, unexpected '$' for when the line

$this->pb->Push();

is called.

I guess its because it does not know that $pb is a PushBot object at this stage ?

Can I not declare it something like :

Public Pushbot $pb;

Upvotes: 0

Views: 91

Answers (1)

webbiedave
webbiedave

Reputation: 48897

Parse error: syntax error, unexpected '$' for when the line

This is a parse error, meaning your code has not even been run yet. Check your code for any sytnax errors (the code you posted does not contain the syntax error).

how in PHP I can specify that $pb is a PushBot object

Although unrelated to the syntax error, if you were using some sort of dependency inversion you could use type-hinting to require a certain object to be passed:

// will cause fatal error if anything other than an object of type Pushbot is passed
function __construct(Pushbot $pb)

Upvotes: 1

Related Questions