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.

8 Answers 8

8

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://web.archive.org/web/20130302084638/http://interfacelab.com/metadataattributes-in-php/

1
  • This looks like it's the closest to what I'm looking for. Thanks so much, Andy.
    – Stepppo
    Dec 22, 2009 at 16:24
2

The accepted answer from Andy Wilson links to pages which are no longer available. I managed to get to the page itself through http://web.archive.org/web/20130116184636/http://interfacelab.com/metadataattributes-in-php/ but the code download the author refers to is a dead link too.

However I've since found a great implementation of PHP Annotations here: https://github.com/mindplay-dk/php-annotations

The only downside I've found so far is that is relies on your file names and class names being the same and of the same case which with Code Igniter they aren't but once I'd worked this out I soon had it all working and of course this limitation wouldn't affect all implementations.

0
1

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.

0

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;
}
0

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

0

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;
        }
    }
}
0

As other answers mentioned, with PHP below 5.0 it wasn't possible, however since PHP 5.0 it is possible to mimic C# functionality using DocComment

I took the idea from this question and modified it for purpose of this question. It is possible to use a JSON string as DocComment to make it easier to parse later and access them using reflection from your code as below

<?php
/** {"Description":"This is a test class"} */
class User {

   /** {"Message":"Please enter a user name."} */
   public $Username;

   /** {"Message":"Please enter a user name."} */
   public function Login($username) {
        print "Inside `aMemberFunc()`";
    }
}

$rc = new ReflectionClass("User");  // class name
print $rc->getDocComment()                          . "<br />\n"; // Get Class comment
print $rc->getMethod("Login")->getDocComment()      . "<br />\n"; // Get Method comment
print $rc->getProperty("Username")->getDocComment() . "<br />\n"; // Get Property comment

?>

With following results

/** {"Description":"This is a test class"} */
/** {"Message":"Please enter a user name."} */
/** {"Message":"Please enter a user name."} */

Going further from here should be easy, remove DocComment markers and parse it as JSON to have an object with your properties. There are more reflection methods available such as getting list of properties, methods and constants, which you can read about it at PHP reflection manual

Note: Compiling with Zend and such, will remove comments from your code and they will not be available, thus you will need to configure your platform to leave comments alone.

0

I used doc comments in reflection. See more info ReflectionClass::getDocComment

Here is example code from my project

/**
* You can use doc comments in reflection. 
* See more info https://php.net/manual/en/reflectionclass.getdoccomment.php
* 
* @role("admin")
*/
class permissiontest extends Page
{
    public function render($p)
    {
        echo 'Howdy friend!';
        //$this->renderView($p);
    }
}

Reflection

class handler 
{
    public function OnPageRendering($page)
    {
        $r = new ReflectionClass(get_class($page));
        $s = $r->getDocComment();
        if (!str::isNullOrEmpty(trim($s))) {
            // tags::pre($s);
            /**
             * @role("filter")
             */
            $matches = array();
            //@role("filter") https://regex101.com/
            preg_match('/@role\(\"(.*)\"\)/', $s, $matches);
            if (!arrays::isNullOrEmpty($matches)) {
            // tags::pre($matches);//Array ( [0] => @role("filter") [1] => filter ) 
            // tags::pre($matches[0]);//@role("filter")        
            // tags::pre($matches[1]);//filter
                $filter = $matches[1];
                //tags::h("Check Permission for:".$filter);
                if (!userHasRights($filter)) {
                    die('You do not have permission on this page! Process stopped!');
                }
            }

        }


    }
}
function userHasRights($right) {
    return false;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.