views:

126

answers:

5

Is there such a thing?

I'd like to do something like this in PHP but I can't see how to do it from the PHP docs:

public class User : ValidationBase
{  
  [NotNullOrEmpty(Message = "Please enter a user name.")] 
  public string UserName { get; set; } 
}

What I'm looking for is the PHP equivalent of an ASP.NET/C# property attribute, which in the above example is signified by the [NotNullOrEmpty(Message = "Please enter a user name.")] line above the property declaration.

+1  A: 

No, there is not, at least not natively supported by PHP.

You can use a framework that will provide with validation for forms, for instance. The Zend Framework has a Zend_Form class that allow to specify if fields are required, what type they should be, and the error message to display if it's not the case.

Wookai
A: 

There is no such thing in PHP, you'll actually have to code it.

A bit like this, I suppose :

public function setUserName($str) {
    if (empty($str)) {
        throw new Exception('Please enter a user name.');
    }
    $this->userName = $str;
}

public function getUserName($str) {
    return $this->userName;
}
Pascal MARTIN
A: 

I think some frameworks can bring this kind of functionality, but PHP is not designed to provide such high-level constructs.

Arno
+3  A: 

PHP has no built-in mechanism for declaring attributes, but it is possible to simulate this behavior using some custom code. The basic idea is to place your metadata in a comment block, and then write a class that parses that comment block. This is less convenient than C# because you need to ensure that your comment "attributes" are formatted properly, but it works.

Here is an example of how to do this: http://interfacelab.com/metadataattributes-in-php/

Andy Wilson
This looks like it's the closest to what I'm looking for. Thanks so much, Andy.
Stepppo
A: 

php does not have properties nor property attributes.

if you'd like to do something similar in php, you'd have to declare a private field, and write public getter and setter methods, and do some sort of null checking within the setter method.

class User extends ValidationBase
{
    private $userName;
    public function GetUserName()
    {
        return $this->userName;
    }
    public function SetUserName($val = '')
    {
        if ($val === '')
        {
            return false;
        }
        else
        {
            $this->userName = $val;
            return true;
        }
    }
}
hyun