9

I have a class called contact:

class contacts
{
    public $ID;
    public $Name;
    public $Email;
    public $PhoneNumber;
    public $CellPhone;
    public $IsDealer;
    public $DealerID;
}

At some point in my code I would like to point to a property within that class and return the name of the property.

<input type="text" 
   id="<?php key($objContact->Name)" ?>"
   name="<?php key($objContact->Name)" ?>"
   value="<?php $_POST['contact'.key($objContact->Name)]" />

My issue being that the key() function only deals with arrays or objects. $objContact->Name itself does not meet these requirements. I know it would be just as simple to type the name itself out into the ID and NAME fields but this is for other code verification uses. Imagine the processor page:

$objContact = new contact();

$objContact->Email = $_POST[$objContact->Email->**GetSinglePropertyName()**];

$objContact->PhoneNumber = $_POST[$objContact->PhoneNumber->**GetSinglePropertyName()**];

This allows me to turn on STRICT and ensure that as I'm writing I'm not creating any fat finger errors along the way that are going to have me denting my head anymore than it presently exist.

UPDATE WITH ANSWER Answer provided by: linepogl

Now I've taken linepogl's idea and extended is some so it can work very easily with my existing code base. Here's what I've come up with:

class baseData {
    public $meta;

    public function __construct() {
        $this->meta = new Meta($this);
    }
}

class Meta {
  public function __construct($obj) {
    $a = get_object_vars($obj);
    foreach ($a as $key => $value){
      $this->$key = $key;   
    }
  }
}

class contacts extends baseData
{
    public $ID;
    public $Name;
    public $Email;
    public $PhoneNumber;
    public $CellPhone;
    public $IsDealer;
    public $DealerID;
}

Which means I can now call the following code with the desired results:

$objContact = new contacts();
echo($objContact->meta->Email);
6
  • 1
    I'm having a hard time figuring out what you want to accomplish. As a single object is just that: a single object, how would the key of the current pointer have any meaning? What do you want to do with key, why, and how should that have a meaning for your object? Commented Mar 4, 2011 at 21:29
  • You cannot get the 'name' of a variable, from a variable. However you can get all of a objects properties name using get_object_vars Commented Mar 4, 2011 at 21:32
  • maybe doing a foreach on you object would help you, not perfect but good for a start Commented Mar 4, 2011 at 21:36
  • If you know the name to supply to some key() like function, then you already have the name... (Remember that any piece of data could have multiple, differently named variables pointing to it.) Maybe you really just need the $objContact->$dynamic_property syntax. Commented Mar 4, 2011 at 21:37
  • 1
    @Shad - Because using strings as pointers to values within an object that will be committing back such sensitive data isn't a good enough method for me. Using a more OOP approach is what I would like to use. And since it is doable and more readable it makes sense all the way around. I think the question here would be why NOT? Commented Mar 5, 2011 at 3:10

4 Answers 4

9

So, you want when you type $objContact->Name to take as an answer not the evaluation of this expression but its meta data, which in this case is a ReflectionProperty object.

What you want is a feature that is called metaprogramming ( http://en.wikipedia.org/wiki/Metaprogramming ). Of course php does not support that but there are other languages that do, such as Lisp etc. Rumors say that C# 5.0 will introduce such features.

You can achieve a similar effect by using Reflection ( http://php.net/manual/en/book.reflection.php ). You can get the meta-object of $objContact (ReflectionClass) and iterate over the properties.

So, there is no way to identify a specific property with an identifier. The only way to do is is with a string of its name.

EDIT:

Yet, there a way to simulate it! Write a class like this:

class Meta {
  public function __construct($obj) {
    $a = get_object_vars($obj);
    foreach ($a as $key => $value){
      $this->$key = $key;   // <-- this can be enhanced to store an
                            //     object with a whole bunch of meta-data, 
                            //     but you get the idea.
    }
  }
}

So now you will be able to do this:

$meta = new Meta($objContact);

echo $meta->Name;   // <-- with will return 'Name'!
Sign up to request clarification or add additional context in comments.

2 Comments

Not the answer I wanted but seeming plausibly correct. I've looked in PHP's ReflectionObject and thus far haven't found exactly how it could be used successfully. It doesn't help that the functions I'd would like to investigate are not documented on php.net.
My only reason for being upset is that I can't vote up more than once for such an answer. GENIUS! I started to try to come up with a similar idea within the class but failed miserably. This will work beautifully and can be made to integrate nicely as a base class to inherit from so I can do something more along the lines of $objContact->Meta->Name;
2

You can use get_object_vars() like this:

$properties = get_object_vars($objContact);
foreach($properties as $name => $value)
{
    if($value == $objContact->Name)
    {
       //here's youre name
    }
}

but with this you will have to assume that $objContact->Name has unique value over all properties...

Comments

0

The key() function works very well with objects. It just doesn't accomplish what you are seemingly trying to do.

$c = new contacts;
end($c);
print key($c);    // "DealerID"

You can foreach over object attributes, and PHP remembers the last accessed key(). But I'm not sure if this is what you want.

4 Comments

That's really close - except when writing the value of the key to the INPUT field I won't be necessarily accessing the field prior to, so this won't work.
@Jeff: I've reread it. The crux of your question is I would like to point to a property. I'm assuming you simply want to output a list of attributes as a form. If so you will have to iterate over the attribues anyway foreach ($contact as $key=>$value) and there is your pointer. You can do $object->$key and just use $key for outputting the <input> fields.
Are you then suggesting to build the INPUT fields within the foreach statement? Or is suggestion to build an array of $keys that can be referenced later?
@Jeff. Yes, I think foreaching is a proper way to do it - if the attributes are in the correct order and you actually want an input field for each of them.
0

As alluded to by konforce, is this what you are looking for?

$var = 'Name';
$Obj->$var;//Obj's Name property
...
id="<?php $var ?>" //id="Name"
...
$_POST['contact'.$var];//$_POST['contactName']

2 Comments

Yeah - not exactly. Using variable variables still leaves the possibility of referencing an item within the class that doesn't truly exist. I could do $var='sillytalk'; $obj->$var and the value is null when used elsewhere because the property of 'sillytalk' doesn't exist.
@Jeff, you can use $foo = new ReflectionProperty('contacts', $var) to check if $var contains a valid property name for the contacts class. It will throw a (catchable) exception if it doesn't.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.