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()

?>
kalaba2003
  • 1,231
  • 3
  • 20
  • 33
  • 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. – Mike B Jun 05 '12 at 20:41

2 Answers2

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)
Eric Petroelje
  • 59,820
  • 9
  • 127
  • 177
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").

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149