dr200166 2013-09-26 18:29
浏览 38
已采纳

将类和方法的属性插入类的一些好方法是什么?

Ok, the problem is that I am using a class, which depends on external configuration to work and validate things but, since these properties are so many in quantity, I would like to know, how to import them.

So, imagine this is the class:

   class doSomething{

        public function __construct($conn){
            $this->conn = $conn;
        }

        public function validateURL($url){
            //do something with $url
        }

        public function validateName($name){
            //do something with $name
        }

        public function validateAge($age){
            // process age
        }

        public function lookEmailInDatabase($email, $table){
            // process data
        }

   }

Now, lets assume the above is inside a files called doSomthingClass.php

So, lets asume, that I have another class to declare values for those properties

function declareProperties($val){

    $conn = new PDO(...);
    $url = 'http://foo.com';
    $name = 'john';
    $age = '17';
    $email = 'simon@yahoo.com';
    $table = 'foobartar';

    return $val;


}

Now, the question is, what would be very efficient, best way to export those properties into this class, as I am not even sure, if the settings should be written inside a function, or another class ..

  • 写回答

2条回答 默认 最新

  • doulu3808 2013-09-26 18:45
    关注

    How about using magic methods __get() and __set():

    public $vars = array();
    
    public function __get( $key )
    {
        if( isset( $this->vars[$key] ) )
        {
            return $this->vars[$key];
        {
        else
        {
            return false;
        }
    }
    
    public function __set( $key, $value )
    {
        $this->vars[$key] = $value;
    }
    

    And for an example: let's say $row is the data. If you use column names as property names (which is also good practice if you planned your structure well) you might make a method like this:

    public function load( $row )
    {
        if( is_array( $row ) )
        {
            foreach( $row as $key => $value )
            {
                $this->$key = $value;
            }
            return true;
        }
        return false;
    }
    

    Edit:

    You don't necessarily even have to pass in the variables like this, you can use the public methods externally:

    $foo = new foo( $db );
    
    $foo->bar( $three, $external, $params );
    

    Does this work for your application?

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

报告相同问题?