如何“通过”类属性到类方法?

发布于 2024-09-10 09:52:20 字数 257 浏览 2 评论 0原文

如何以以下方式“传递” eventName 到 dbSafe() ?这可能吗? dbSafe() 会是什么样子?

$eventClass->eventName->dbSafe();

我猜 dbSafe() 大致如下所示:

public function dbSafe() {
     return mysql_real_escape_string($this);
}

How can I "pass" eventName to dbSafe() in the following fashion? Is this possible? What would dbSafe() look like?

$eventClass->eventName->dbSafe();

I'm guessing dbSafe() would look roughly like this:

public function dbSafe() {
     return mysql_real_escape_string($this);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷默言语 2024-09-17 09:52:20

您可以将每个属性封装在一个公开 dbSafe() 的新类中。这有点像过于简单的装饰器模式。

class Property {
    private $value;
    function dbSafe() {
        return addslashes($this->value); //substitute for your function
    }
    function __construct($v) { $this->value = $v; }
}

class Event {
    function __get($name) { 
        return new Property($name);
    }
}

$e = new Event;
echo $e->{"df'\\"}->dbSafe();

You could encapsulate every attribute in a new class that exposed dbSafe(). It's kind of like an oversimplified decorator pattern.

class Property {
    private $value;
    function dbSafe() {
        return addslashes($this->value); //substitute for your function
    }
    function __construct($v) { $this->value = $v; }
}

class Event {
    function __get($name) { 
        return new Property($name);
    }
}

$e = new Event;
echo $e->{"df'\\"}->dbSafe();
绿光 2024-09-17 09:52:20

如果 $event 是一个类的实例,具有名为 eventName 的属性和名为 dbSafe 的方法,那么也许您想要这样做:

$safeName = $event->dbSafe ('eventName');

public function dbSafe ($propertyName){
  return mysql_real_escape_string($this->$propertyName);
}

但是,将数据转义合并到所有类中并不是一个好主意,就像您在这里所做的那样。您确实需要中央数据库管理代码来处理所有转义,这样您就不会忘记它。

If $event is an instance of a class with a property called eventName and a method called dbSafe, then maybe you want to do this:

$safeName = $event->dbSafe ('eventName');

public function dbSafe ($propertyName){
  return mysql_real_escape_string($this->$propertyName);
}

BUT, it's not a great idea to incorporate your data escaping into all of your classes, as you seem to be doing here. You really want central database management code that handles all escaping so you can't forget it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文