0

I'm starting learning classes in PHP. I 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?

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

One question, I don't have to run any code to get the $authtoken, just the user provides it. What code do I have to put there?
@Francesc: Then you can create the constructor but don't do anything with it :)
And then If I want to use the $tokenID in the other functions of the class, I only have to use that variable, is it right?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.