3

I tried $this-> but could not assign a value to $first_name and $last_name variable. Without removing static feature of the function and without inserting static feature to variables, how can I echo full_name()? Here is the code :

<?php

class User  {

    public $first_name;
    public $last_name;

  public function full_name() {
    if(isset($this->first_name) && isset($this->last_name)) {
    return $this->first_name . " " . $this->last_name;
    } else {
    return "No name!";
    }
   }

  public static function verify() {

    $this->first_name = "firstname";
    $this->last_name =  "last_name";
   }
  }

$user = new User();
User::verify();
echo $user->full_name()

?>
1
  • 7
    You can't. Static methods have no context so there's nothing to validate unless you pass something in. There's workarounds of course.. like making your object a singleton. But that wouldn't make much sense in your User example. Commented Jun 5, 2012 at 20:41

2 Answers 2

7

You can't. Why not make verify a member function and call it like

$user->verify();

Another alternative would be to pass the user into the verify function, like this:

public static function verify( $user ) {
   $user->first_name = 'firstname';
   $user->last_name = 'last_name';
}

and call like so:

User::verify($user)
Sign up to request clarification or add additional context in comments.

Comments

4

You can't really... other then using the singleton pattern, which rather defeats the point of a static function.

The basic idea is that a static function doesn't require an instance, but what you're trying to do does.
I'd suggest verifying the data in a non-static setter function, or in the constructor. Or, if needs must, add a public method verify that isn't static.
Think about it: statics don't need an instance, so what are you verifying, if there is no instance (and therefore no "$this").

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.