Reflection or Object Orientation?

I’m learning PHP from PHP Novice to Ninja and somewhere in the book the author uses “reflection” to get the constants of an entity class(User) to do a bit-wise operation and compare them against data stored in database about each user to realize the level of access and privileges of each of them.

Now, the problem is, in the introduction section, as soon as this problem was posed by the author, I thought to myself I would pass an instance of the User entity class to this class(it’s called “Register” and it is a controller) and then I would be able to use those constants that are defined in it. But then he solved this problem using “reflection”. I understand how it works but I don’t understand how one reaches this conclusion to use “reflection” instead of “object orientation”.
Please explain this to me.

Hi mojtabaavahdati,

You’re right that you could do this without reflection, but reflection here is useful because the class contains constants that represent each permission:


class Author {

  const EDIT_JOKES = 1;
  const DELETE_JOKES = 2;
  const LIST_CATEGORIES = 4;
  const EDIT_CATEGORIES = 8;
  const REMOVE_CATEGORIES = 16;
  const EDIT_USER_ACCESS = 32;
  // …


For the administration side of things a form is required to assign each permission to a given user. A checkbox is required for each of the permissions in the class.

Rather than creating a HTML template with a hardcoded checkbox for each permission e.g.

<input type="checkbox" value="1" <?php if ($author->hasPermission(EDIT_JOKES)) {
    echo 'checked';
} ?> Edit Jokes
<input type="checkbox" value="2" <?php if ($author->hasPermission(DELETE_JOKES)) {
    echo 'checked';
} ?> Delete Jokes
<!-- and another box for each template -->

I used reflection to generate a list of permissions from the class and then loop over them, allowing the use of a loop rather than needing to manually write a checkbox for each permission:

  <?php foreach ($permissions as $name => $value): ?>
    <input name="permissions[]" type="checkbox" value="<?=$value?>"
      <?php if ($author->hasPermission($value)): echo 'checked'; endif; ?> 
     />
    <label><?=$name?>

$permissions here is a list of constants from the class. The advantage of this approach is that to add a new permission, you just have to add a new constant to the class and it automatically appears in the list of checkboxes. Without using reflection, you’d have to manually edit the template file to add the checkbox each time a new permission was added to the website.

I hope that helps clear things up and I’ll try to make the reasoning clearer for the next revision of the book.

3 Likes

Now it’s perfectly clear Tom. Thank you very much.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.