问题
I have written a database class but can't access the method from within:
class database{
.
.
private $mgc;
private $real;
public function insert($table,$values,$row = null){
.
.
for($i = 0; $i < count($values); $i++){
$values[$i] = safe_value ($values[$i]);
}
.
.
}
public function safe_value( $value ) {
if( $this->real ) {
if( $this->mgc ) { $value = stripslashes( $value ); }
$value = mysql_real_escape_string( $value );
}
else {
if( !$this->mgc ) { $value = addslashes( $value ); }
}
return $value;
}
}
When running this class I have this error:
Fatal error: Call to undefined function safe_value()
When I used mysql_real_escape_string
instead of the safe_value
method the class works perfectly. Why can't I access the safe_value
function and why is it showing me this error?
回答1:
When calling a non-static member function from within the class you need to refer to it using $this
, in this particular case you should call it as
$values[$i] = $this->safe_value($values[$i]);
回答2:
You need to change the call to $values[$i] = $this->safe_value($values[$i]);
for non-static methods. For static methods, use $values[$i] = database::safe_value($values[$i])
.
来源:https://stackoverflow.com/questions/4115753/call-a-function-or-method-from-inside-its-class