简体   繁体   中英

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

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

?>

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM