Php get property
How to Use the PHP __get and __set Magic Methods
In this article, we show how to use the PHP __get and __set magic methods.
The PHP __get and __set magic methods function as getters and setters for object values, but it had the added advantage in that you don’t have to declare the object properties (variables) in the >Instead when you set a value (with the object property never declared in the >The same is true for the __get method. Without the object property being declared in the >So the __get and __set magic methods function as getters and setters, without the object property variable having to be declared in the >We will show each of these in the code below.
In the code below, we make a >Getter and setter methods prov >In this >So passing data first through a method allows us to filter out bad data. It allows for this encapsulation where we don’t have to accept bad data, such as a negative height or 0.5 inches tall.
This is why getter and setter methods are commonly used.
So we create a >Ins >The first method that we create the setter method using the __set function. The setter function has to accept 2 parameters, the object property you are defining and the value of this object property. As we are setting a child’s height in this code, the height is the object property and the value of the height we set it to is the value. We make it so that if the value passed into the object property is greater than 30, we set the object property to that value. If the value is less than 30, then the magic set method does not set the value.
We then create the next function, the getter method using the __get function. The get function accepts one parameter, the $property of the object. We do not need the $value as the parameter, because the $value is already set by the setter function. With the getter function, we do not set the value. We just retrieve the value that’s already been set. So in this getter function, we return the child’s height in inches by calling the $this->property function. $this->property refers to the value of the property of the object we’re getting.
All of this will make more sense now below.
So underneath this, we create an object of the k >We then the object property, height, of $k >What’a amazing about the magic method __set() in PHP is that we have defined the property variable $height anywhere in the >So because we automatically set an object property and its height without declaring them or calling a function, this automatically calls the PHP __set() magic method. So the $property value is height. The $value of this property is 45. We set the value only if the value is greater than 30. We set the value through the line, $this->property= $value. $this refers to the object kid1. We set $kid->height= 45. So now you can see how this is set through the PHP __set magic method.
This covers the set part.
To automatically get the property of an object, you call an output function such as echo or print with the parameter of an object and property. This automatically triggers the PHP __get magic method.
The only parameter needed for the __get() method is the $property variable. We return out what the child’s height is in inches.
So this is all that is required to use the PHP __get and __set magic methods. It’s very adaptable because you don’t need to declare variables in the >Running the PHP code above yields the following output shown below.
get_object_vars
(PHP 4, PHP 5, PHP 7)
get_object_vars — Возвращает свойства указанного объекта
Описание
Возвращает видимые нестатические свойства указанного объекта object в соответствии с областью видимости.
Список параметров
Возвращаемые значения
Возвращает ассоциативный массив нестатических свойств объекта object , доступных в данной области видимости.
Список изменений
Версия | Описание |
---|---|
5.3.0 | Функция теперь возвращает NULL , если object не является объектом. Ранее возвращался FALSE . |
Примеры
Пример #1 Пример использования get_object_vars()
class foo <
private $a ;
public $b = 1 ;
public $c ;
private $d ;
static $e ;
public function test () <
var_dump ( get_object_vars ( $this ));
>
>
$test = new foo ;
var_dump ( get_object_vars ( $test ));
Результат выполнения данного примера:
Смотрите также
- get_class_methods() — Возвращает массив имен методов класса
- get_class_vars() — Возвращает объявленные по умолчанию свойства класса
User Contributed Notes 38 notes
You can still cast the object to an array to get all its members and see its visibility. Example:
class Potatoe <
public $skin ;
protected $meat ;
private $roots ;
function __construct ( $s , $m , $r ) <
$this -> skin = $s ;
$this -> meat = $m ;
$this -> roots = $r ;
>
>
$Obj = new Potatoe ( 1 , 2 , 3 );
echo «n» ;
?>
code till dawn,
mark meves
This is a slight modification of the previous poster’s function. We ran into a problem using this function when we had a JS array nested inside a JS hash.
Something like this.
myHash = new Hash();
myHash[address] = new Array();
When we threw that at this function, it found the first hash as an object, and then using the previous poster’s function, it did not consider the array as an «object.» Instead it gave us a std_object type and we were unable to make any use of it.
The modification we made was adding a check for is_array inside both the is_object and is_array checks when you call the function. This checks for an array inside either an object or a nested array.
function conv_obj($Data) <
if(is_object($Data))<
foreach(get_object_vars($Data) as $key=>$val) <
if(is_object($val) || is_array($val)) <
$ret[$key]=conv_obj($val);
>else <
$ret[$key]=$val;
>
>
return $ret;
>elseif(is_array($Data)) <
foreach($Data as $key=>$val) <
if(is_object($val) || is_array($val)) <
$ret[$key]=conv_obj($val);
>else <
$ret[$key]=$val;
>
>
return $ret;
>else <
return $Data;
>
>
To add to my previous comment — the error message should have meant same structure.
As my implementation called for cross-class comparison.
this example will look like all values of vars was set in your class. write a method like the name: dumpClass and then fill in follow code:
echo «class vars«;
foreach( $vars as $name => $value ) <
echo »
«.$name.» : «.$value;
>
look at: get_object_vars($this);
In case your object contains again objects (and so on), this function might be useful:
function makeAssoc($res) <
$res = get_object_vars($res);
while (list($key, $value) = each($res)) <
if (is_object($value)) <
$res[$key] = makeAssoc($value);
>
>
return $res;
>
Furthermore, variables not declared in the class but set on a given object, will be returned by get_object_vars().
$test = new MyTest();
// This var isn’t declared in the class
$test->newObjVar = ‘foobar’;
The output is:
Array
(
[classVar1] => Class Var 1
[classVar2] => class var 2
[classVar3] =>
[newObjVar] => foobar
)
Prior to version 4.2, classVar3 would not be output as it was never assigned a value.
Also note that this is recursive. For example:
private $Father ;
private $Mother ;
public function __construct () <
$this -> Father = NULL ; //I don’t know Sarah’s Father
$this -> Mother = NULL ; //I don’t know Sarah’s Mother
>
>
class John_Connor <
private $Father ;
private $Mother ;
public function __construct () <
$this -> Father = $this ; //John went back in time and fathered himself
$this -> Mother = new Sarah (); //Sarah was his mom and his mate ewww
>
public function showParents () <
return get_object_vars ( $this );
>
>
$John = new John_Connor ();
var_dump ( $John -> showParents ());
?>
You will see this outputs:
array(2) <
[«Father»]=>
object(John_Connor)#1 (2) <
[«Father»:»John_Connor»:private]=>
object(John_Connor)#1 (2) <
[«Father»:»John_Connor»:private]=>
*RECURSION*
[«Mother»:»John_Connor»:private]=>
object(Sarah)#2 (2) <
[«Father»:»Sarah»:private]=>
NULL
[«Mother»:»Sarah»:private]=>
NULL
>
>
[«Mother»:»John_Connor»:private]=>
object(Sarah)#2 (2) <
[«Father»:»Sarah»:private]=>
NULL
[«Mother»:»Sarah»:private]=>
NULL
>
>
[«Mother»]=>
object(Sarah)#2 (2) <
[«Father»:»Sarah»:private]=>
NULL
[«Mother»:»Sarah»:private]=>
NULL
>
>
Subject: using «sql_calc_found_rows» in a MySQL query while exploiting result in a PHP db class object.
There is a nice function in MySQL that allows to know how many records would have been returned if no «where» clause were set : SQL_CALC_FOUND_ROWS.
If you have create a db object to collect the returned lines, you will be a little perplex when trying to call the result of this function.
Why ?
Simply because the returned field’s name is «found_rows()» and obviously it’s not possible to call something like :
-> found_rows () ?>
. as it will try to acces a method, not a property !
Then, the only way to get the right result seems to be the use of a class function, like :
-> query ( «select found_rows()» );
$count = current ( get_object_vars ( current ( $db -> result )));
?>
Of course, if somebody found an other way to solve it, like a special syntax (see the one used with curled arrays in a string), I’m really open to discuss.
In PHP5 to get an array with all properties (even the private ones) all you have to do is write a public method that returns an array for your class:
public function getArray()
<
return get_object_vars($this);
>
Have BEAUTIFUL day 🙂
Since there’s no apparent means of obtaining all the *private* properties in an object I wrote a little function to do it. Built in support would be much more efficient since mine uses a preg_ search to do this.
function get_private_properties ( $obj , $inside = false )
<
$obj_dump = print_r ( $obj , 1 );
preg_match_all ( ‘/^s+[(w+):private]/m’ , $obj_dump , $matches );
if ( $inside )
<
$output = array();
foreach ( $matches [ 1 ] as $property )
<
$output [ $property ] = $obj -> $property ;
return $output ;
>
>
else return $matches [ 1 ];
>
?>
So if you run it with the optional second paramter missing you’ll just get an array of the variable names that are private inside the class. This is the only option if you are not inside the actual object and the object has no private properties inherited.
If you run it with the second parameter set to true you will get an associative array with the properties and their corresponding values. I’d only advise to do that for singletons since you may get errors if there are any private properites in parents/children.
Hmmm. A bit embarassing.
It turns out the best way to get references to all of your objects member variables is NOT with the functions I provided before, or with get_object_vars.
Just cast the object to array.
# The two following statements are now equivalent and identical
$a[«member»]=3;
$obj->member=3;
A very powerful tool, for inspectors and what not.
In case your object contains again OBJECTS or ARRAYS:
function makeAssoc($res) <
if (is_object($res)) $res = get_object_vars($res);
while (list($key, $value) = each($res)) <
if (is_object($value) || is_array($value)) <
$res[$key] = makeAssoc($value);
>
>
return $res;
>
Thanks to mark at dreamzpace dot com
# How to make a function change the private attributes
# from some object without use serialize functions or
# lose the control of the changes.
/**
* Parent Class to allow the change of privates attributes
* Look the abstract function __setAttribute.
*
* @author Renan de Lima ( renandelima@gmail.com )
* @author Thiago Mata ( thiago.henrique.mata@gmail.com )
* @date 2007-02-21
*/
abstract class father
<
/**
* Receive the Aray and try to change the attribute value
*
* @param array $arrNewValues
*/
public function __fromDatabase ( $arrNewValues )
<
$arrToSet = array_intersect_key ( $arrNewValues , get_object_vars ( $this ) );
foreach( $arrToSet as $strAttribute => $mixValue )
<
$this -> __setAttribute ( $strAttribute , $mixValue );
>
>
/**
* Required method to control the attributes of class
* @param string $strAttribute
* @param unknown $mixValue
*/
abstract protected function __setAttribute ( $strAttribute , $mixValue );
/**
* Just a example of a child class using the functionality
*
* Note: if you don’t wanna to allow the change of some attribute
* by this method you can just make more complex the __setAttribute function.
*
* @author Renan de Lima ( renandelima@gmail.com )
* @author Thiago Mata ( thiago.henrique.mata@gmail.com )
* @date 2007-02-21
*/
class son extends father
<
/**
* This is the most simple implementation of the method.
* This way it’s allowed to the parent class change any attribute
* @param string $strAttribute
* @param unknown $mixValue
*/
protected function __setAttribute ( $strAttribute , $mixValue )
<
$this -> < $strAttribute >= $mixValue ;
>
$objSon = new son ();
$objSon -> __fromDatabase ( array( ‘atr’ => 55 ) );
var_dump ( $objSon );
?>
Get Image Properties using PHP
The data or Information that are associated with an image is called as metadata of the images. For example, image type, image width, and height, attributes, created date, last modified date and etc.
This information are not obvious to the user on simply viewing the images. In this article, we have to see how to get metadata of images using PHP script.
PHP provides various functions and DLL to extract image properties from an image. These functions are,
- imagesx() and imagesy()
- getimagesize()
- exif_read_data()
The corresponding DLL to be enabled for using these functions are php_mbstring.dll, php_exif.dll. For that, we should search for these all names among php.ini, and could be found as,
And then, enable this DLL by removing semicolon(;) at the beginning of each line. And the order should be as shown above to enable mbstring before exif.
imagesx() and imagesy()
The imagesx() and imagesy() are used to extract the width and height of the images respectively. For that, it accepts the resource type of data which will be returned on creating new images dynamically using PHP script. For example, PHP captcha code is created dynamically as images to ensure that the input of web application is entered by the human. If we want to check the width and height of the captcha we have created, then, imagesx() and imagesy() could be used appropriately.
getimagesize()
This PHP method that returns an array of image properties like width, height, image type, mime type and etc. This method will return a limited amount of image data. But, there is no need to send resource data of the image as the argument of this function. Rather, we should specify the path of the image file, which can be either relative or absolute path.
The following PHP program is used to extract the properties of an image. For that, we need to access HTML form data on submitting the selected image file.
First, create HTML content to select the image file for which we need to extract properties. As we have seen, to upload files through HTML form, we need to specify the enctype attribute to the form. But this attribute can be used, if the form method is posted, as like as the following content.
After that, we need to access these from data from a PHP script to be embedded on top of the above content. And the PHP script is,
This script will be executed on submitting the form, and the image file is added to PHP global array, that is, $_FILES. After ensuring that the $_FILES is not empty, then, we should specify the name of the file to getimagesize() as shown above. Finally, image properties are returned as an array and displayed to the browser, in human readable format, by using PHP print statement inside pre tags.
exif_read_data()
Since getimagesize() functions will return limited set of properties, exif_read_data() is used to get more information further associated with images. So, added to the width, height information, it will return a huge list of additional information such as image created date, last modified date, File name, size, orientation, resolution and etc.
This function will be used to extract properties of digital images in which Exif data is stored in its header. Exif is a standard format, that can be expanded as Exchangeable Image Format.
Image types are of 16 totally, which varies based on the devices used to capture images. Image types are returned as numbers that are associated with the available types of images like gif, png and etc. For example, if image type returned as 2 denotes that, it is JPEG image.
Not only the type of the images but also the entire list of image properties returned by this function, will also be varied depends on devices.
In the above program, replace the line which invokes getimagesize() function, that is,
by the following line for getting image properties in EXIF format.
And, let us experiment with different images captured by different devices, to see the differences between the resultant property array will be returned.
Drupalize.Me
Join today and get instant access to our tutorials.
Dynamically Access PHP Object Properties with $this
I got the opportunity to field this question that was emailed into support today in regards to the video Writing Custom Field Handlers Continued. This video is part of our Coding For Views For Drupal 7 series.
In the file «databasics_handler_field_percent.inc», what does the following notation mean?
From what I could gather it roughly means I’m accessing the view object from the row object, but I’m not sure. I could run dsm($row) and dsm($row-><$this->aliases[‘nid’]>) , but dsm($row-><$this>) didn’t work.
What’s the relation between $row and $this ? What does $this stand for?
Would you please clarify?
thank you in advance!
It’s a great question, and I thought I would answer it with a blog post since I can see how it would be confusing.
First off, is what does $this mean? In Object Oriented PHP, $this is a special «pseudo» variable inside the scope of a method that is part of a class that refers to this particular instance of this class. It’s a way of allowing an object to reference itself. For more information on the $this variable check out our video Work with PHP Class Methods around the 2 minute mark.
Given this line of code, the objective is to retrieve the $nid value from the $row object. However, in this particular case, we don’t know what the name of the property on $row is that contains the value we’re after.
Here’s a slightly simpler example of a similar thing. Let’s say we want to access the $row->my_nid property. We could do it like this:
Or, alternately, this would achieve the same thing:
Using the -> <$nid_property>notation says, evaluate the variable $nid_property , and substitute its value with the name of the property to access. So PHP eventually interprets this as $row->my_nid . The beauty is that $nid_property can be set based on some other logic that determines, through whatever means, what the property name ought to be.
That’s exactly what’s going on here:
When you create a new View with the Views UI, it’s possible to add the same field any number of times. Or, to do something like add the node.title field and then add the node.title field of a different node pulled in through a reference. Whenever you add a field to a View the Views module needs to create a unique name for that field to use in the corresponding SQL query. MySQL doesn’t like it when you try and select two columns with the same name, so instead you create aliases, and you’ll need a way to access the individual values in the PHP representation of the row returned from MySQL. This isn’t exactly what Views would produce, but it’s close enough to illustrate the problem being solved.
When this query is performed by Views the result is stored in the $row variable. The properties match the names of the aliases used in the query, so we have one named «node_1_id» and one named «node_2_nid». Both generated on-the-fly by Views. None named simply «nid». So when you want to retrieve the NID value you need to know the name of the alias. Those are stored by Views in the $this->aliases property of the Views object.
So we end up with this code to get the value of the NID:
Which, has the effect of looking up in the $this->aliases array what the value of the nid key is, and then substitutes the resulting value into the $row-><> expression and you end up with something like $n >node_1_id .
Finally, why does this work dsm($row-><$this->aliases[‘nid’]>); , and this dsm($row-><$this>); doesn’t? Because the $this variable, which is a representation of the Views object that’s used to represent the View currently being built (see above) can’t be coerced into a string, and thus there isn’t any reasonable value to use as the name of the property you want to access on the $row object.