I have this code (two classes)
class url
{
private $profile_id;
private $short;
public $notice;
private $forbidden;
function url() {
$this->forbidden = array('index.php', 'index.html', 'styles.css', 'style.css');
if ($_POST['profile_id']){
// global $db;
$exists = db::fetch_one(db::query("SELECT count(1) FROM ".TABLE." WHERE profile_id = ".intval($_POST['profile_id']).";"));
$exists_username = db::fetch_one(db::query("SELECT count(1) FROM ".TABLE." WHERE url_short = '".db::mres($_POST['url_short'])."'"));
}
}
}
class db
{
function db(){
mysql_connect("localhos开发者_开发技巧t", "root", "h1gh§c1a0");
mysql_select_db("gplus") or die(mysql_error());
mysql_set_charset("utf8") or die(mysql_error());
}
function query($query){
// print_r( $this);
$result = mysql_query(self::protect($query)) or _log("Query failed: ".$query);
//$this isn't working
//$result = mysql_query($this->protect($query)) or _log("Query failed: ".$query);
return $result;
}
function fetch($result){
$result = mysql_fetch_assoc($result);
return $result;
}
function fetch_one($result){
$result = mysql_fetch_row($result);
return $result['0'];
}
function mres($text) {
return mysql_real_escape_string($result);
}
function protect($text) {
if (preg_match("/UNION/i", $text)) {
_log("Hack attempt: ".$text);
die();
}
// die($text);
return $text;
}
}
$db = new db();
$url = new url();
my problem is, that this line
$result = mysql_query(self::protect($query)) or _log("Query failed: ".$query);
works, but when I change self::
with $this->
it's throwing error
Fatal error: Call to undefined method url::protect() in /data/my/db.php on line 71
how is it possible? I thought that $this->function();
calls method in current class. What am I doing wrong?
In url
constructor, you're calling db::query
statically, therefore, protect()
will be called statically as well and, hence, $this
will not be available.
You can either keep it all static or you can inject an instance of db
into url
:
$db = new db();
$url = new url($db);
When using db::query()
, you are accessing db in a static way (you are calling a class method, instead of an instance method). Therefore, there is nothing to access via $this, as $this returns the pointer to a class instance, while self
is a reference to the class itself.
If you would use $db->query()
, $this->protect()
would also work.
精彩评论