How to write short PHP functions that work together - php

I want to modularize functions, but this is not working...
class Review {
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
private function get_survey($db, $n){
// Query the DB for a certain survey number
if($n == 1){
// Perform some logic
} else {
// Perform some other logic
}
return $a_survey;
}
};
Using the class like this..
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
PHP throws this:
Fatal error: Using $this when not in object context in Review.class.php
Thanks for the help!

Your design pattern is good, you just have a syntax error. You have missed the $ sign on your method calls in show_report(), it should look like this:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}
Also, the semicolon at the end of the class is unnecessary.
Finally, as another person mentioned, you need to call show_report with parameters, like this:
echo $r->show_report($db, $id);

Inside your function show_report($db, $id) is the this pointer without the prefixing $ sign which causes the syntax error. Additionally in the second part the function isn't called with parameters.
The function has to look like that:
public function show_report($db, $id){
// Query the DB on $id
$x = $this->get_survey($db, 1);
$y = $this->get_survey($db, 2);
// Use x and y to build a report
return $a_report;
}

echo $r->show_report;
In this example, you are attempting to call the function with no arguments. If this is really what you are doing, that would be at least one problem.
Instead, call the function with arguments:
echo $r->show_report('foo', 1);

Thank you all. I fixed all the syntax errors, thanks to https://stackoverflow.com/a/19258788/1004107. This is the root of the issue I do believe:
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo Review::show_report($db, $id);
?>
</p>
Should be...
<?php
include_once('api/Review.class.php');
$r = new Review();
?>
<p>
<?php
echo $r->show_report($db, $id);
?>
</p>
And this is do to static context? Please comment.

Related

Check if method is false then output results

I have a class that contains a method which carries out various database checks. It then returns the value, if exists.
Here is a very basic setup example:
PHP Class
class myClass{
var $aVar1;
var $aVar2;
function myMethod()
{
// database query
// if results from query return **results**
// else return false
}
}
HTML/PHP File
// setup $myClass object var
<?php if($myClass->myMethod(): ?>
// lots of html
<?php echo $myClass->myMethod() ?>
// lots of html
<?php endif; ?>
This occurance happens multiple times throughout my file with different methods. My question is, I am calling the method initially and checking if it's false and then calling it again to echo the output.
I could do the following but would end up with a variable declaration on every method. There must be a more professional approach?
<?php
$myMethod = $myClass->myMethod();
if($myMethod): ?>
// lots of html
<?php echo $myMethod ?>
// lots of html
<?php endif; ?>
Is there a cleaner more efficient way of doing this?
Age old problem. One common technique is to store the return val in a temporary variable
$result=$myClass->myMethod();
if($result!=FALSE)
echo $result;
You can also use a simpler version
if($result=$myClass->myMethod())
echo $result;
And you can also use the simplest one!
echo $myClass->myMethod() ?: '';
Simpler than the simplest one!
echo $result=$myClass->myMethod();
You can do this to reduce verbosity:
<?php
function foo($bool = true) {
$result = array();
if($bool) {
$result = array('bar');
}
return $result;
}
if(! array()) {
echo 'empty array evaluates to false.';
}
if($result = foo()) {
var_export($result); // Will dump array with 'bar'.
}
if($result = foo(false)) {
var_export($result); // Won't happen.
}
If your return is truish then the contents of the if will execute.

Avoid running function more than once

Hi what would be a better way to write the following code so myScript() isn't executed several times?
<?php
function myScript($myVar){
//some code
return $anotherVar;
}
$data = myScript("some input");
echo $data.$data.$data;
$data variable just storing the output its not execute several time when you echo the variable .
In your script the function execute only once. you use the return value more and more.
The function never run alone, it is you who can call for a function to
run.
function myScript($myVar){
return $anotherVar; //5
}
$data = myScript("some input");
echo $data.$data.$data; //555
You can also call this function multiple time if you want different values for different parameter like:
function myScript($myVar){
return $myVar * $myVar;
}
$data1 = myScript(3);
$data2 = myScript(4);
$data3 = myScript(5);
echo $data1." - ".$data2." - ".$data3; //9 - 16 - 25

Handling multiple variable results

So here is my case:
I have three functions performing some chemical reactions(synthesis1(), synthesis2() & synthesis3() ).
All of these functions will give an answer or a fail in the results.
They were originally separate scripts but are now in a class.
NB: the functions work fine by themselves, even in the class.
Below is my script to instantiate the class and start the functions.
My problem is that since i am running a reaction which fires all the functions;
i get one 1 correct answer and two fails or three fail at once.
What is the best way to handle the situation.
I want one correct answer and suppress the two fails or just show one fail in case of three fails(all fails). I don't expect three right answers.
P.s. All answers are strings.
<?php
// create an object for class name
$aaa = new synthesis();
$abc = new synthesis();
$abcd = new synthesis();
// call the functions in the class
$synthesis1 = $aaa->synthesis1();
$synthesis2 = $abc->synthesis2();
$synthesis3 = $abcd->synthesis3();
// call the if functions
$searches = array($synthesis1, $synthesis2, $synthesis3);
foreach($searches as $search) {
if ($aaa->synthesis1($search)){
echo 'Match found: ' . $search;
break;
}
elseif ($abc->synthesis2($search)){
echo 'Match found: ' . $search;
break;
}
elseif ($abcd->synthesis3($search)){
echo 'Match found: ' . $search;
break;
}
else{ echo"Please try again or try another reaction";}
}
?>
I don't know why you need to instantiate three different objects if you have three individually named methods.
I would think you might want to add a method to your class to simply run all synthesis methods all at once and return the result. So something like:
class synthesis {
protected $synthesis_methods = array(
'synthesis1',
'synthesis2',
'synthesis3',
// add more methods here if needed
}
public function synthesis1() {
// your method logic here
}
public function synthesis2() {
// your method logic here
}
public function synthesis2() {
// your method logic here
}
public function synthesize_all() {
$result = false;
$i = 0;
while(false === $result && $i < count($this->synthesis_methods)) {
$result = call_user_func(array($this, $this->synthesis_methods[$i]));
$i++;
}
return $result;
}
}
You would then only instantiate a single object. Usage would be:
$synth_obj = new synthesis();
var_dump($synth_obj->synthesize_all());
An easy way to handle this is to use OR logic:
if($aaa->synthesis1($search) or $abc->synthesis2($search) or $abcd->synthesis3($search))
{
echo "Match Found: $search";
break;
}
else
{
echo "Please try again or try another reaction.";
}

Which variables should be set as the properties of a class in php?

<?php
class oopClass{
function __construct($editingtext, $searchfor, $replacewith){
if(!empty($editingtext) && !empty($searchfor) && !empty($replacewith)){
$editingtext = str_replace($searchfor,$replacewith,$editingtext);
echo $editingtext;
}else{
echo 'All Fields Are Required.';
}
}
}
//closing php
The code is working , but as there is no properties of the class are set which is a bad practice, which variables of this code should be set as a class property and why?
There are other things wrong with your code, and it is not the absence of properties. You are constructing an object and in the constructor you output the result. THAT is bad practice.
I'd fix it something like this:
class TextReplacer {
var $search;
var $replace;
function __construct($s, $r) {
$this->search = $s;
$this->replace = $r;
}
function replace($text) {
// your code, using the properties for search and replace, RETURNING the result
return $ret;
}
}
then call like:
$oo = new TextReplacer("bar", "baz");
echo $oo->replace("let's replace some bars in here");
In short:
Nothing wrong with not using properties, if your class is designed like that.
Please use useful class, method and variable names.
Don't do more than one thing in a method ("side effects").
Don't output the result, but return it. It is up to the user of the class to decide what happens to the results.
(most importantly): Think before you code.
It's not necessarily bad practice if the above code is ALL you plan on doing with this code. If you needed to expand its functionality, I might imagine $editingtext could be a property.
class oopClass{
private $editingtext;
function __construct($editingtext, $searchfor, $replacewith){
$this->editingtext = $editingtext;
if(!empty($this->editingtext) && !empty($searchfor) && !empty($replacewith)){
$this->editingtext = str_replace($searchfor,$replacewith,$this->editingtext);
echo $this->editingtext;
}else{
echo 'All Fields Are Required.';
}
}
}
//closing php

problem with using $GLOBALS and global keyword

i have this code in actions.class.php
public function executeListmatches(sfWebRequest $request)
{
$form_values = $request->getParameter('match_form', array());
global $gender_id2 = $form_values['gender2'];
global $age1 = $form_values['age1'];
$age2 = $form_values['age2'];
$province_id = $form_values['id'];
echo "in list matches ".$gender_id2." ".$age1." ".$age2." ".$province_id;
$this->pager = $this->setupPager();
$this->matching_rows = RcProfileTablePeer::getAllBySelection($gender_id2,$age1,$age2,$province_id);
return sfView::SUCCESS;
}
and then
protected function setupPager()
{
echo "in pager ".$gender_id2." ".$age1." ".$age2." ".$province_id;
$pager = new sfPropelPager('RcProfileTable', 10);
$pager->setCriteria(RcProfileTablePeer::getAllBySelection($GLOBALS['gender_id2'],$GLOBALS['age1'],$GLOBALS['age2'],$province_id));
$pager->setPage($this->getRequestParameter('page', 1));
$pager->init();
return $pager;
}
when i use the global keyword i get and error:
PHP Parse error: syntax error, unexpected '=', expecting ',' or ';' in actions.class.php on line 41
when i use $GLOBALS['gender_id2'] the value is null
i need to setup a pager because i need to list all rows that matches my selection criteria
in RcProfileTablePeer i have:
static public function getAllBySelection($gender2,$age1,$age2,$province_id)
{
echo $gender2." ".$age1." ".$age2." ".$province_id;
$criteria = new Criteria();
$criteria->add(RcProfileTablePeer::GENDER_ID,$gender2, Criteria::EQUAL);
$criteria->add(RcProfileTablePeer::AGE,$age1,Criteria::GREATER_EQUAL);
$criteria->addAnd(RcProfileTablePeer::AGE,$age2,Criteria::LESS_EQUAL);
if ($province_id <> 10)
$criteria->addAnd(RcProfileTablePeer::PROVINCE_ID,$province_id, Criteria::EQUAL);
return self::doSelect($criteria);
}
please help, i dont know how else i must do this.
thank you
There just is a parse error in your code. The PHP interpreter tells you this. You can't declare a global variable, and assign it in one statement.
global $gender_id2 = $form_values['gender2'];
must be
global $gender_id2;
$gender_id2 = $form_values['gender2'];
Other than that, as OZ_ already stated, don't use globals.

Categories