PHP, scope resolution with variable passed - php

$columnToChange = $this->getColumnName($questionNo); //Gets EXAMHIST_Q2_JUGDGE
$conn = Propel::getConnection(ExamHistoryPeer::DATABASE_NAME);
//Update the approriate question with user answer in exam history table;
$selectCriteria = new Criteria();
$selectCriteria->add(ExamHistoryPeer::EXAM_HISTORY_ID, $examHist->getExamHistoryId());
$updateCriteria = new Criteria();
//This shows fatal error
$updateCriteria->add(ExamHistoryPeer::$columnToChange, $userAnswer);
//$updateCriteria->add(ExamHistoryPeer::EXAMHIST_Q2_JUGDGE, $userAnswer); //This works
BasePeer::doUpdate($selectCriteria, $updateCriteria, $conn);
Fatal error: Access to undeclared static property: ExamHistoryPeer::$columnToChange
Can any of you guys, please tell me why can not this works, and how to make it work with
ExamHistoryPeer::$columnToChange

PHP is thinking that you want to get static property not constant. It's because of $ sign in ExamHistoryPeer::$columnToChange.
Instead use constant('ExamHistoryPeer::columnToChange') to get values of that constant.

You could maybe do this ?
$oReflection = new ReflectionClass(ExamHistoryPeer);
//Value of the Constant
$mValue = $oReflection->getConstant($columnToChange);

Related

Using Dynamic Variable Names to Call Static Variable in PHP

I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"

CodeIgniter access model with $$ fails

I have a model called Treatment in CodeIgniter. I want to load and use this model 'dynamically'. That is, I don't want to have to call it directly by name (I am trying to generalize some code to use whatever model I tell it).
So, I do this:
$namespace = 'blah';
$modelName = 'Treatment';
...
$this->load->model($namespace . '/' . $modelName);
$this->model = $this->$$modelName;
However, I get an error when accessing the $this->$$modelName variable, saying that the variable 'Treatment' is undefined:
Undefined variable: Treatment ... Fatal error: Cannot access empty
property in /mydir/application/controllers/rest/base_rest.php on line
202.
Where line 202 is the line where I am using the $this->$$modelName variable.
Now, if I changed line 202 to be:
$this->model = $this->Treatment;
It works fine.
Does anyone know why I can't seem to use the PHP $$ syntax here?
You can't because it's not a supported syntax. Try
$this->{$modelName}
instead. e.g.
php > class foo { public $bar = 42; }
php > $x = new foo();
php > $y = 'bar';
php > echo $x->$$y;
PHP Notice: Undefined variable: bar in php shell code on line 1
PHP Fatal error: Cannot access empty property in php shell code on line 1
php > echo $x->{$y};
42php >

Error While instance a object from a String PHP

My problem is quite similar to this post: [a link]Creating PHP class instance with a string I want to instance an object from a String however my string came from a object property, I have this:
$type = strval($act->elementtype); $ty="Client";
$societe = new $type;
if I change $societe = new $ty it will work but no for $societe = new $type even when $type is equal to Client which is the name of my class. I recieve:
Fatal error: Class 'Client ' not found in....
It does't seem to be true that $type contains the same as $ty:
Fatal error: Class 'Client ' not found in....
^
You can use var_dump() to trouble-shoot this kind of stuff.
Well.. If someone needs the answer sometime, the think was the type of my variable in my BD elementtype was type CHAR so I try to change it in posgresql and set it into CHAR VARYING and it works!! Hope it help! ^^

PHP Class Variable Access

Seems like a simple enough question, so my apologies for asking. As a precursor I'm not necessarily 'new', but rather not so well-versed in PHP.
I have a class, declared as follows:
class User
{
public $id = "";
public function User()
{
$this->$id = isset($_COOKIE['userid']) ? $_COOKIE['userid'] : 0;
}
}
Which seems simple enough, however - upon construction, I get the following set of errors:
Notice: Undefined variable: id in D:\xampp\htdocs\sitecore\include\classes.php on line 13
Fatal error: Cannot access empty property in D:\xampp\htdocs\sitecore\include\classes.php on line 13
Sorry for asking something so simple. The line in question starts with "$this->$id".
Remove the $ symbol at the 'id' place:
$this->id = isset($_COOKIE['userid']) ? $_COOKIE['userid'] : 0;

net.sf.jasperreports.engine.design.JRValidationException - Query parameter not found

I use JasperServer and PHP JavaBridge to generate PDF reports via JasperServer inside PHP. I get compile error because of missing (unassigned) parameter passed to JRXML compiler
Fatal error: Uncaught [[o:Exception]:
"java.lang.Exception: Invoke failed:
[[c:JasperCompileManager]]->compileReport((o:String)[o:String]).
Cause: net.sf.jasperreports.engine.design.JRValidationException:
**Report design not valid** : 1. **Query parameter not found** : db_field_id VM:
1.6.0_18#http://java.sun.com/" at: #-12
net.sf.jasperreports.engine.design.JRAbstractCompiler.verifyDesign(JRAbstractCompiler.java:258)
I cant find a way to pass my
$params = new Java("java.util.HashMap");
foreach ($jrxml_params as $key => $jr_param) $params->put($key, $jr_param);
list of params to the compile method nor I can disable this verification by
$japser_props = new JavaClass("net.sf.jasperreports.engine.util.JRProperties");
$japser_props->COMPILER_XML_VALIDATION = false;
Here is what I use to generate PDF (works fine if JRXML file doesn't contain $P{} pamareters and halts otherwise)
$class = new JavaClass("java.lang.Class");
$class->forName("com.mysql.jdbc.Driver");
$driverManager = new JavaClass("java.sql.DriverManager");
$conn = $driverManager->getConnection("jdbc:mysql://localhost:3306/XXX?user=XXX&password=1234");
$compileManager = new JavaClass("net.sf.jasperreports.engine.JasperCompileManager");
$report = $compileManager->compileReport(realpath("/www/some.jrxml"));
$params = new Java("java.util.HashMap");
foreach ($jrxml_params as $key => $jr_param) $params->put($key, $jr_param);
$jasperPrint = $fillManager->fillReport($report, $params, $conn);
$exportManager = new JavaClass("net.sf.jasperreports.engine.JasperExportManager");
$outputPath = realpath(".")."/"."output.pdf";
$exportManager->exportReportToPdfFile($jasperPrint, $outputPath);
How do I avoid this error, I know what I need to pass and I don't know a way to do it, can't I just pass params to fillManager?
$japser_props = new JavaClass("net.sf.jasperreports.engine.util.JRProperties");
$japser_props->setProperty('net.sf.jasperreports.compiler.xml.validation',true);
this is the way to set property from PHP but that's not the problem. It turns out everything was fine, I've missed parameter declaration before my MySQL query... Put
<parameter name="db_field_id" class="java.lang.Integer">
in your JRXML before you use it as $P{db_field_id} now it compliles fine and later
$jasperPrint = $fillManager->fillReport($report, $params, $conn);
parameters are assigned at fill time

Categories