PHP: Get Parent Class Property Values - php

I have an Abstract class that is extended by a child class.
I need to retrieve an array of all the properties and their values for the abstract class, from within a method inside the abstract class.
Is there a simpler way to do this other than this code:
$options = get_object_vars($this);
foreach ($options as $var => $value) {
if (!property_exists(get_class(), $var)) {
unset($options[$var]);
}
}
get_object_vars($this) returns all the properties and their values, but includes the properties of the child class - which I don't want.

$options = get_class_vars(get_class());
foreach($options as $key=>$val)
echo $key . " : " . $val . " => " . $this->$key;
This will give an output as
Propertyname : standardvalue => dynamic value

Related

How can I check if a object is an instance of a specific class?

Is there a way to check if an object is an SimpleXMLELement?
private function output_roles($role) {
foreach ($role as $current_role) {
$role_ = $current_role->attributes();
$role_type = (string) $role_->role;
echo "<tr>";
echo "<td><b>" . $role_type . "</b></td>";
echo "</tr>";
$roles = $role->xpath('//role[#role="Administrator"]//role[not(role)]');
if (is_array($roles)) {
$this->output_roles($roles);
}
}
}
This is my function and the $role->xpath is only possible if the provided object is a SimpleXMLElement. Anyone?
You can check if an object is an instance of a class with instanceof, e.g.
if($role instanceof SimpleXMLElement) {
//do stuff
}
The following methods and operators are useful to determine whether a particular variable is an object of a specified class:
$var instanceof TestClass: The operator “instanceof” returns true if
the variable $var is an object of the specified class (here is:
“TestClass”).
get_class($var): Returns the name of the class from $var, which can
be compared with the desired class name.
is_object($var): Checks whether the variable $var is an object.
Read more in How to check if an object is an instance of a specific class in PHP?

php passing and looping an array into a class method

i'm some what new to php classes, so apologies if this is an obvious one.
i'm trying pass an array to a class method, but i get a warning when i try to foreach loop it
Warning: Invalid argument supplied for foreach() in....
the foreach does actually loop the array and gives me the desired result, so i'm confused about the warning, and i'm not finding any simple explanation on how to fix it/ do it the correct way. i also tried passing the array as a json_encode then decoding back to an array once inside the method, and the same warning occurs. what also confuses me, i get nothing if i print_r($this->payload) inside the method.
here's my class...
// class
// --------------------------
class Form {
public $form_action;
public $form_method;
public $form_class;
public $form_role;
public $payload;
function form() {
$output = '';
foreach ($this->payload as $key => $value) {
$output .= '<input type="'.$key.'" name="'.$key.'" ......>';
}
return $output;
}
}
here's the array...
// array
// --------------------------
$my_array = (object)array (
"form1" => (object)array (
"foo1" => "bar1",
"foo2" => "bar2"
)
);
and here's where i pass the array to the class...
// set class
// --------------------------
$set = new Form;
$set->form_action = '';
$set->form_method = 'post';
$set->form_class = 'form-signin';
$set->form_role = 'form';
$set->payload = $my_array->form1;
echo $set->form();
There is no option1 in your array (what is actually object). Anyway, why do you call it array, when its an object? So that will be $my_array->form1
And you are using the same name of your function to show the form, as the name of the class, so that will be the constructor. And there will be no value for $this->payload at the first run.
So your final code will be this:
class Form {
public $form_action;
public $form_method;
public $form_class;
public $form_role;
public $payload;
function showForm() {
$output = '';
foreach ($this->payload as $key => $value) {
$output .= '<input type="' . $key . '" name="' . $key . '" ......>';
}
return $output;
}
}
$my_array = (object) array(
"form1" => (object) array(
"foo1" => "bar1",
"foo2" => "bar2"
)
);
$set = new Form;
$set->form_action = '';
$set->form_method = 'post';
$set->form_class = 'form-signin';
$set->form_role = 'form';
$set->payload = $my_array->form1;
echo $set->showForm();
I can't tell from your warning message. But I think that if you were to look at the stack trace that the warning is being generated via the line $set = new Form;
From the php manual about constructors
For backwards compatibility, if PHP 5 cannot find a __construct()
function for a given class, and the class did not inherit one from a
parent class, it will search for the old-style constructor function,
by the name of the class. Effectively, it means that the only case
that would have compatibility issues is if the class had a method
named __construct() which was used for different semantics.
Because in your example class, your method shares the same name as the class and does not have a __construct method. The form() method is being called when you create the object at which point $this->payload is null.
You can fix this by either creating a __construct method or in your class definition initializing $this->payload to an empty array.

CActiveRecord Iteration not respected Virtual Attributes

i have a model extended from CActiveRecord
let says the name of the class is SomeModel and the object is $foo
$foo = SomeModel::model()->findByPk(1);
Then i created virtual attributes on that model
$foo->setImage('testing.jpg');
When i testing call the property/state it works perfectly:
var_dump($foo->image); // output testing.jpg
But when i do iteration with the model it didn't show the property.
foreach($foo as $key => $value) {
echo $key .' = '. $value."\n";
}
How to make the image property listed when i do iteration?
You can't iterate a model like that. Try this instead:
foreach ( $foo->getAttributes() as $key => $value ) {
// Do stuff
}

Dynamic constants in PHP?

Is there a way to create a class's constants dynamically? I know this sounds a bit odd but let me explain what I'm trying to do:
I have a Enum class who's attributes are defined by static const definitions
This class extends the PHP SplEnum class
Rather than type in each of these definitions in code I'd like to have a static initialiser go out to the database and pull the enumerated values
Maybe somethings like this:
class myEnum extends SplEnum {
public static function init () {
$myNameValuePair = DB_Functions::get_enum_list();
foreach ( $myNameValuePair as $name => $value) {
$const = array ( self , $name );
$const = $value;
}
}
}
I recognise that this won't actually work as it doesn't set CONST's but rather static variables. Maybe my whole idea is hair brained and there's a better technique to this. Anyway, any method to achieve the end goal is greatly appreciated.
UPDATE
I think it might be helpful to be a little more clear on my goals because I think it's entirely possibly that my use of Constants is not a good one. Basically I want to achieve is typical of the Enumerated list's requirements:
Constrain function signatures. I want to be able to ask for a "set" of values as an input to a function. For instance:
public function do_something ( ENUM_Types $type ) {}
Simple and Compact. Allow for a simple and compact syntax when used in code. For instance with the use of constants I might write a conditional statement something like:
if ( $my_var === ENUM_Types::TypeA ) {}
Dynamic enumeration. I'd like this enumeration to be managed through the frontend and stored in the database (I'm using wordpress admin screens for this in case anyone cares). At run time this "list" should be pulled out of the DB and made available to the code as an enumeration (or similar structure that achieves the goals above).
Wrap your "enum" values in a singleton and implement the (non-static) magic __get method:
<?php
class DynamicEnums {
private static $singleton;
private $enum_values;
public static function singleton() {
if (!self::$singleton) {
self::$singleton = new DynamicEnums();
}
return self::$singleton;
}
function __construct() {
$this->enum_values = array( //fetch from somewhere
'one' => 'two',
'buckle' => 'my shoe!',
);
}
function __get($name) {
return $this->enum_values[$name]; //or throw Exception?
}
public static function values() {
return self::singleton()->enum_values; //warning... mutable!
}
}
For bonus points, create a (non-OO) function that returns the singleton:
function DynamicEnums() {
return DynamicEnums::singleton();
}
Consumers of "DynamicEnums" would look like:
echo DynamicEnums::singleton()->one;
echo DynamicEnums()->one; //can you feel the magic?
print_r(DynamicEnums::values());
[edit] More enum-like.
Q: Is there a way to create a class's constants dynamically?
The answer is 'Yes', but don't do that :)
class EnumFactory {
public static function create($class, array $constants) {
$declaration = '';
foreach($constants as $name => $value) {
$declaration .= 'const ' . $name . ' = ' . $value . ';';
}
eval("class $class { $declaration }");
}
}
EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2));
echo darkSide::FOO . ' ' . darkSide::BAR;
Next question...
Q: Constrain function signatures. I want to be able to ask for a "set" of values as an input to a function. For instance: public function do_something ( ENUM_Types $type ) {}
According to the manual, in that case $type is must be an instance of the ENUM_Types class. But for constant it is impossible (they can't contain objects).
But wait... We can use such trick:
class Enum {
protected static $_constantToClassMap = array();
protected static function who() { return __CLASS__; }
public static function registerConstants($constants) {
$class = static::who();
foreach ($constants as $name => $value) {
self::$_constantToClassMap[$class . '_' . $name] = new $class();
}
}
public static function __callStatic($name, $arguments) {
return self::$_constantToClassMap[static::who() . '_' . $name];
}
}
class EnumFactory {
public static function create($class, $constants) {
$declaration = '';
foreach($constants as $name => $value) {
$declaration .= 'const ' . $name . ' = ' . $value . ';';
}
eval("class $class extends Enum { $declaration protected static function who() { return __CLASS__; } }");
$class::registerConstants($constants);
}
}
EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2));
EnumFactory::create('aaa', array('FOO' => 1, 'BAR' => 2));
echo (aaa::BAR() instanceof aaa) ? 'Yes' : 'No'; // Yes
echo (aaa::BAR() instanceof darkSide) ? 'Yes' : 'No'; // No
And after that we can use a "type hinting":
function doSomething(darkSide $var) {
echo 'Bu!';
}
doSomething(darkSide::BAR());
doSomething(aaa::BAR());
Q: Simple and Compact. Allow for a simple and compact syntax when used in code. For instance with the use of constants I might write a conditional statement something like: if ( $my_var === ENUM_Types::TypeA ) {}
You can use values of your pseudo-constants in such form:
if (darkSide::FOO === 1) {}
Q: Dynamic enumeration. I'd like this enumeration to be managed through the frontend and stored in the database (I'm using wordpress admin screens for this in case anyone cares). At run time this "list" should be pulled out of the DB and made available to the code as an enumeration (or similar structure that achieves the goals above).
You can init your enumeration by passing array to the EnumFactory::create($class, $constants):
EnumFactory::create('darkSide', array('FOO' => 1, 'BAR' => 2));
You could do something like Const = $$constant. Then you could set $contant = whatever. OR you could use a protected property since you want it to be dynamic and Constants are not. Example:
class Foo {
protected $test = '';
function set($bar){
$this->test = $bar;
}
function get($bar){
return $this->test;
}
}
$foobar = new Foo();
$foobar->set('test');
echo $foobar->get('test');
I do not recommend it, but eval() ... please don't.
I've modified autoloaders to automatically define Exception types that are missing or misspelled. Reason: You can catch an uncaught exception, but you cannot recover from the PHP_FATAL when instantiating a typo in your exception class.

output constructor variable value in oop php

My concept is very poor in oop for php. My class has a constructor with three parameters.i create a object and pass three values to the constructor. Now, how will i show constructor value.
class Foo {
public function __constructor($para1, $para2, $para3 ){
echo $para1 . '<br>';
echo $para2 . '<br>';
echo $para3 . '<br>';
}
}
$f = Foo(10,20,30);

Categories