How can I assign a value to public variable from inside static function in php?

702 views Asked by At

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

?>
2

There are 2 answers

0
Elias Van Ootegem On BEST ANSWER

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").

0
Eric Petroelje On

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)