简体   繁体   中英

Class static function variable reference in PHP

PHP 7.

I'm trying to use the same class method in different situations. The first time, when the user is creating a new entry into the database, and I draw the admin page with empty values. It has been created as the following.

$classname::drawAdmin(FALSE);

$classname is a variable, since I don't know in advance which classes will be used on the webpage (Ikr?), and have to get it from the database.

Inside the method, it checks if it's creating a new object, or reusing an existing one.

static function drawAdmin( $mod = FALSE ) {
        print 'Technology<input type="text" name="technology" value="'.($mod?$this->technology:"").'" /><br />';
etc...
}

It works well when a new entry is created, check if it's trying to modify, if not, create an input with no value, else it is writing the objects datas into the values.

However it does not work when I create a new object, and try to modify it's data.

$class = new $row['class_name']($_GET['id']);
$class->drawAdmin(TRUE);

(The class' constructor sanitizes the $_GET array.)

In this case, I receive an error message:

Fatal error: Using $this when not in object context in [censored]/class.phone.php on line 932

even if the object was created correctly, and existing (checked with var_dump).

Haha, jokes on me, it's a static method, so I can't use $this! However, when I change the print to:

static function drawAdmin( $mod = FALSE ) {
        print 'Technology<input type="text" name="technology" value="'.($mod?self::technology:"").'" /><br />';
etc...
}

I still get the error message:

Fatal error: Undefined class constant 'technology' in [censored]/class.phone.php on line 932

and if I add the (protected) variables to static, I can't use them anymore with $this->.

Is there any way, that I could use the same class variables with both object and without object contexts?

I think you could keep the method static, but if you're editing an existing object, you'd have to pass an actual instance of the same class into the method as optional second parameter, to be used when $mod is true, and then use the "technology" value from that instance.

For example:

static fuction drawAdmin($mod=FALSE, $class=NULL) { 
        print 'Technology<input type="text" name="technology" value="'.($mod?$class->getTechnology():"").'" /><br />';
}

and then in the case of it being a modification, call it like this:

$class->drawAdmin(TRUE, $class);

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