Home > OS >  Get class prop name in php
Get class prop name in php

Time:08-29

I'm not good at php OOP.

class Example{
    public $name;
    public $age;
}

$example = new Example();

I would like to get the property name as string, like-

echo get_property_name($example->name); //should echo 'name'
//OR,
echo $example->name->toString(); //should echo 'name'

Please note that, I don't want to write the property name in a string or variable like-

$property = $class->getProperty('name');

I don't want to get the value of property, I want to get the name of the property as a string.

Is it possible in php?

CodePudding user response:

You can build a helper function with get_object_vars(). Because you already know the var-name, the function only checks, if this exists in the object and returns the var as string:

function get_property_name($oObject, $sString) {
  $aObjectVars = get_object_vars($oObject);
  if( isset($aObjectVars[$sString]) ) {
    return $sString;
  }
  return false; // object var not exists
}

CodePudding user response:

In PHP you can introspect a class, function, or... with ReflectionClass:

<?php


class Example
{
    public $name;
    public $age;
}

$example = new Example();

$ref = new ReflectionClass($example);

$props = $ref->getProperties();

foreach($props as $prop) {
    var_dump($prop->name);
}

The output:

string(4) "name"
string(3) "age"

CodePudding user response:

one other option would be a trait with following methods.

public function toArray(): array
{
    return (array) $this;
}

public function properties(): array
{
    return array_keys($this->toArray());
}

We do not know your use case. If you write a DTO, Reflection might be your desired way. If you write a model with some extra sugar, you could store all attributes in an array to load and edit them. Probably two arrays so you could compare edited and loaded values. with __isset, __get, __set you can always preload attributes.

  • Related