2009-06-03 5 views
0
class person { 

    var $name; 
    var $email; 

    //Getters 
    function get_name() { return $this->name; } 
    function get_email() { return $this->email; } 

    //Setters 
    function set_name($name) { $this->name = $name; } 

    function set_email($email) { 

     if (!eregi("^([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[@]([0-9,a-z,A-Z]+)([.,_,-]([0-9,a-z,A-Z]+))*[.]([0-9,a-z,A-Z]){2}([0-9,a-z,A-Z])*$", $email)) { 
      return false; 
     } else { 
      $this->email = $email; 
      return true; 
     } 

    }//EOM set_email 

}//EOC person 
+2

サイドノートでは、eregとそのバリエーションはPHP 5.3以降で償却されています。現在はpregのみが使用されています。 – charlesbridge

答えて

9

ユーザー名とメールアドレスを格納するクラスです。 set_email()メソッドは、指定されたアドレスをチェックして、格納前に有効かどうかを確認します。

eregiファンクションは、正規表現を使用して電子メールアドレスをチェックします。これらは、文字列の操作と解析を実行する非常に強力な方法ですが、その特定の例は、おそらく最良の導入ではありません。正規表現の使用を始めたばかりの方には、Perl compatible regular expressionsがより広く使用されており、より強力であることが分かります。さらに、ereg functions will be deprecated from PHP5.3+

ここにはone source of introductory informationがあります。遊んで正規表現をテストするには、Regex Coachのようなアプリを使用することをおすすめします。それを打破するには

^       # force match to be at start of string 
([0-9,a-z,A-Z]+)   # one or more alphanumerics 
([.,_,-]([0-9,a-z,A-Z]+)) # followed by period, underscore or 
          # dash, and more alphanumerics 
*       # last pattern can be repeated zero or more times 
[@]      # followed by an @ symbol 
([0-9,a-z,A-Z]+)   # and one or more alphanumerics 
([.,_,-]([0-9,a-z,A-Z]+)) # followed by period, underscore or dash, 
          # and more alphanumerics 
*       # last pattern can be repeated zero or more times 
[.]      # followed by a period 
([0-9,a-z,A-Z]){2}  # exactly two alphanumerics 
([0-9,a-z,A-Z])*$   # then the remainder of the string must be 
          # alphanumerics too - the $ matches the end of the 
          # string 

をすべての有効な電子メールアドレスの100%マッチする正規表現の書き方はかなり複雑であり、これは大多数と一致します簡略化パターンです。ここにはwriting email address regex patternsに関する良い記事があります。

10

人に関する情報を格納するためのデータクラスです。また、電子メールの検証も行います。 set_emailメソッドに無効な電子メール(この場合、正規表現と一致しない文字列)を渡すと、このメソッドはfalseを返します。

+0

+プログラマーは数年前にそれを書いたか、 __set($ key、$ value)と__get($ key)の魔法の機能について聞いたことがありません。 –

+1

これはオブジェクトのPHP4構文であるため、何年も前に書かれていたでしょう。 – dragonmantank