douling8087 2011-06-07 07:36
浏览 50
已采纳

如何从PHP中的其他类使用STATIC方法访问类属性?

the question title seems pretty confusing, but this is what i want to achieve.

i have two classes

1. Category
2. Validation

In Category Class i have the following Class Property

public  $error;    //holds all errors in an array.
private $dbh;      //Database object Handle(PDO).
private $validate; //Holds Validation Object
private $data = array('categoryName',
                      'subCategoryName',
                      'prefix',
                      'categoryId',
                      'subCategoryId');

in Validation Class i have defined a method.

public function required($fields = array()) {
    foreach($fields as $field) {
        if(empty(__CLASS__::data[$field])) {

        }
    }
}

now when i call the method $this->validate->required() within the class Category it should check the condition if $data[field] of Category class is empty or got any value in it. hence i have used the following syntax which does not seems to work. if(empty(__CLASS__::data[$field]))what the condition should check is if the class property $data of the class it is being called from (it is class Category in this case) is empty or not. what is the correct syntax for fetching the class property dynamically?

thank you..

  • 写回答

4条回答 默认 最新

  • dso89762 2011-06-07 07:53
    关注

    Give your Category instance as parameter to your validation function. You should have something like this:

    public function required($category, $fields = array()) {
        foreach($fields as $field) {
            if(empty($category->data[$field])) {
    
            }
        }
    }
    
    $this->validate->required($this);
    

    Also you do not use a static method, as mentioned in your questions headline in your example. If you have a static function in Validation you would call it like this:

    Validation::required($this);
    

    In this case, you do not need a reference to a Validation instance in your Category class at all.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行