开发者

Passing a string when calling the constructor of a class in PHP

I'm starting learning classes in PHP. I开发者_Python百科 coded that:

class User {
    function getFbId($authtoken) {
        
    }
    function getFbFirstName ($authtoken) {
    
    }
}

What I want to do is something like that: $user=new User($authtoken); And pass the $authtoken to the class. It's possible to define that when starting the class. It's possible to retrieve that value inside a function of that class?


To use the variable passed in constructor throughout your class, you can create a class level variable like this:

class User {
    private $tokenID = NULL;

    function __construct($tokenID){
      // store token id in class level variable
      $this->tokenID  = $tokenID;
    }
    
    function someFun($authtoken) {    
      echo $this->tokenID;
    }
}

You need to create the constructor in order to do that:

class User {

    function __construct($tokenID){
      // do something with $tokenID
    }
    
    function getFbId($authtoken) {    
      // code
    }
    
    function getFbFirstName ($authtoken) {
     // code
    }
}

Note:

If you are using PHP4, a constructor can be created with a function name same as that of class like:

class User {

    function User($tokenID){
      // do something with $tokenID
    }
    
    function getFbId($authtoken) {    
      // code
    }
    
    function getFbFirstName ($authtoken) {
     // code
    }
}

Now you can do something like:

$user = new User($authtoken);


You are looking for contructors. See http://www.php.net/manual/en/language.oop5.decon.php Or http://www.codewalkers.com/c/a/Programming-Basics/ObjectOriented-PHP-Constructors-and-Destructors/ for a walk through.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜