How to set class variables dynamically? - php

Consider the following code:
class Project
{
public $ProjectID;
}
class Work
{
public $WorkID;
}
public function insert($pData, $tableName)
{
//generate insert here
$pData->{$tableName . 'ID'} = $result->getId();
}
$p = new Project();
$w = new Work();
insert($w, 'Work');
insert($p, 'Project');
echo $p . ' -- ' . $w;
Now how would I go about setting the variable in a dynamic way? I'm building a data layer. The $pData->{$tableName . 'ID'} doesn't seem to work...

So, you want to dynamically call setters?
$y = new stdClass();
$y->prop1 = "something";
$targetProperty = "prop1";
$y->$targetProperty = "something else";
echo $y->prop1;
//Echos "something else"
That what you're looking for?

This is what you're looking for:
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data->$name = 7;
}
The property name can be a variable. Just like functions:
$p = 'print_r';
$p('StackOverflow');
For future reference: if you need this statically, you're looking for variable variables,
public function set_to_seven($p_data, $name)
{
$name = $name . 'ID';
$p_data::$$name = 7;
}

You can set public properties by accessing them just like any other definition in the class.
$p = new Project();
$p->ProjectID = 5;
echo $p->ProjectID; // prints 5
http://php.net/manual/en/language.oop5.visibility.php

This worked for me.
class Project {
public $ProjectID;
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p->ProjectID;
You just need to echo the variable or set up a toString function on the class to echo the class. To String works like this
class Project {
public $ProjectID;
public function __toString(){
return (string)$this->ProjectID;
}
}
function setToSeven($pData, $name) {
$pData->{$name . "ID"} = 7;
}
$p = new Project();
setToSeven($p, 'Project');
echo $p;

Related

Method not working outside of the class it is in

Functions are not working due to undefined variables and I have no clue why that is. I think I just don't get the scope at which objects/classes work. Do I need to make a reference like $obj from which to call the functions? If so why is it not working in this example?
<?php
class employee {
// Properties
public $name;
public $salary = 0;
// Methods
function set_name($name) {
$this->name = $name;
}
function get_name() {
return $this->name;
}
function set_salary($salary) {
$this->salary = $salary;
}
function get_salary() {
return $this->salary;
}
function populate()
{
$worker = array();
$worker[0] = new employee();
$worker[0]->set_name('Linda');
$worker[0]->set_salary(5800);
$worker[1] = new employee();
$worker[1]->set_name('Manuel');
$worker[1]->set_salary(2750);
$worker[2] = new employee();
$worker[2]->set_name('Luis');
$worker[2]->set_salary(3200);
$worker[3] = new employee();
$worker[3]->set_name('Carly');
$worker[3]->set_salary(2999);
$i = 0;
}
function checkTaxes()
{
while ($i < 4)
{
echo "Name: " . $worker[$i]->get_name();
echo " - Salary: " . $worker[$i]->get_salary();
if ($worker[$i]->get_salary() >= 3000)
{
echo " - You have to pay taxes!<br><br>";
}
else
{
echo " - You don't have to pay taxes!<br><br>";
}
$i++;
}
}
}
$obj = new employee;
$obj->populate();
$obj->checkTaxes();
?>
$worker is undefined in checkTaxes()
If you want to use $worker in checkTaxes() or other functions, you should define $worker in class employee with private $worker = [];, just like $name and $salary.And after that, you can update it in populate() with $this->worker[0] = xxx;, and read it in checkTaxes() with $this->worker[$i]->getxxx.

Class is not recognized within php file

I am a beginner in php. I want to call a class within the same php file but when i am trying the class itself is not recognized. What i am doing wrong. please guide me through the right direction since i just started writing code in php.
Code:
<?php
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
Somemethod("Have some calculations over here");
Class studdetails{
public id;
public name;
public roll;
}
?>
There are some syntax errors. Missing ";" and "$".
<?php
Class studdetails {
public $id;
public $name;
public $roll;
}
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
?>
In php you need to prefix class properties with $ sign.
See the example bellow
$sid = 1;
$sname = 'name';
$sroll = 'sroll';
$details = new studdetails();
$details->id = $sid;
$details->name = $sname;
$details->roll = $sroll;
Somemethod("Have some calculations over here", $details);
Class studdetails
{
public $id;
public $name;
public $roll;
}
function Somemethod($str, $obj) {
echo $str . PHP_EOL;
var_export($obj);
}

How return a value from one class function to another class function in PHP

I am trying to get the value of a varibale if a condition is tru from one class function to another class function.
Could you please let me know how do i do this(I am new to PHP.)
Code:
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
}
}
Class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$test = $var1;
echo "$test";
}
Here you can see I need $var1 variable value from ErrorList class to Error class.
Thanks in advance.
Regards,
Tejesh.B
<?php
class ErrorList{
static function getErrorsSince($delay, $criteria = NULL) {
global $appsFeXref, $table_error,$table_error_dis, $table_occurrence, $table_status, $table_fe_parameters, $debugMode;
if ($criteria->isValid()){
$var1 = '123';
return $var1;
}
}
}
class Error{
function initFromDb($initDetails = false) {
global $appsFeXref, $table_error, $table_status, $table_fe_parameters, $table_error_dis;
$details = ($initDetails)? ", s.last_time, s.last_time_origin, s.last_time_machine, s.last_time_text, s.last_time_peak, ed.comment ":"";
$call_class = new ErrorList();
$get_val = $call_class->getErrorsSince();
$test = $get_val;
echo $test;
}
}
?>

How to get all public properties of a class as json?

Consider following example:
<?php
class p{
public $name = 'jimmy';
public $sex = 'male';
private $age = 31;
// there should be more unknow properties here ..
function test(){
echo $this->name;
}
function get_p_as_json(){
// how can i get json of this class which contains only public properties ?
// {"name":"jimmy","sex":"male"}
}
}
$p = new p();
$json = $p->get_p_as_json();
echo $json;
Question: How to get all public properties of a class as JSON?
You just create another class q extends from p. And then the code looks like following:
class p {
public $name = 'jimmy';
public $sex = 'male';
private $age = 31;
// there should be more unknown properties here ..
function test(){
echo $this->name;
}
}
class q extends p {
function get_p_as_json($p) {
return json_encode(get_object_vars($p));
}
}
$q = new q();
$p = new p();
$json = $q->get_p_as_json($p);
echo $json;
$a = array();
$reflect = new ReflectionClass($this /* $foo */);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $prop) {
/* here you can filter for spec properties or you can do some recursion */
$a[ $prop->getName() ] = $a[ $prop->getValue()];
}
return json_encode($a);
Since the public members can also be accessed outside of the class..
Accessing members outside of the class
$p = new p();
foreach($p as $key => $value) {
$arr[$key]=$value;
}
Demo
Accessing the public members within the class by making use of ReflectionClass
<?php
class p{
public $name = 'jimmy';
public $sex = 'male';
private $age = 31;
// there should be more unknow properties here ..
function test(){
echo $this->name;
}
function get_p_as_json(){
static $arr;
$reflect = new ReflectionClass(p);
$props = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach ($props as $prop) {
$arr[$prop->getName()]=$prop->getValue($this); //<--- Pass $this here
}
return json_encode($arr);
}
}
$p = new p();
echo $json=$p->get_p_as_json();
Demo
The best way to do this would not be to call a method of the class, per se.
However, you could initiate the following:
$myPublicMethodsInJson = json_encode(get_class_methods($p));
However, you would not be able to call get_class_methods from within the class because it will return ALL of your methods, private and public. When you call it from outside of the class it will only return the public methods.

How to instantiate object of $this class from within the class? PHP

I have a class like this:
class someClass {
public static function getBy($method,$value) {
// returns collection of objects of this class based on search criteria
$return_array = array();
$sql = // get some data "WHERE `$method` = '$value'
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$new_obj = new $this($a,$b);
$return_array[] = $new_obj;
}
return $return_array;
}
}
My question is: can I use $this in the way I have above?
Instead of:
$new_obj = new $this($a,$b);
I could write:
$new_obj = new someClass($a,$b);
But then when I extend the class, I will have to override the method. If the first option works, I won't have to.
UPDATE on solutions:
Both of these work in the base class:
1.)
$new_obj = new static($a,$b);
2.)
$this_class = get_class();
$new_obj = new $this_class($a,$b);
I have not tried them in a child class yet, but I think #2 will fail there.
Also, this does not work:
$new_obj = new get_class()($a,$b);
It results in a parse error: Unexpected '('
It must be done in two steps, as in 2.) above, or better yet as in 1.).
Easy, use the static keyword
public static function buildMeANewOne($a, $b) {
return new static($a, $b);
}
See http://php.net/manual/en/language.oop5.late-static-bindings.php.
You may use ReflectionClass::newInstance
http://ideone.com/THf45
class A
{
private $_a;
private $_b;
public function __construct($a = null, $b = null)
{
$this->_a = $a;
$this->_b = $b;
echo 'Constructed A instance with args: ' . $a . ', ' . $b . "\n";
}
public function construct_from_this()
{
$ref = new ReflectionClass($this);
return $ref->newInstance('a_value', 'b_value');
}
}
$foo = new A();
$result = $foo->construct_from_this();
Try using get_class(), this works even when the class is inherited
<?
class Test {
public function getName() {
return get_class() . "\n";
}
public function initiateClass() {
$class_name = get_class();
return new $class_name();
}
}
class Test2 extends Test {}
$test = new Test();
echo "Test 1 - " . $test->getName();
$test2 = new Test2();
echo "Test 2 - " . $test2->getName();
$test_initiated = $test2->initiateClass();
echo "Test Initiated - " . $test_initiated->getName();
When running, you'll get the following output.
Test 1 - Test
Test 2 - Test
Test Initiated - Test

Categories