Accessing variable stored in class from another file - php

I would like to access the $new_id variable in the method below (from public class youth_teams) from an outside file but I can't figure out how. I have it printing the lastInsertID correctly from inside the file which contains the method but would like to be able to access the variable in other files also.
public function addTeam(
$team_name,
&$error
) {
$query = $this->pdo->prepare('INSERT INTO `' . $this->table . '` (
`team_name`
) VALUES (
:team_name
)');
$query->bindParam(':team_name', $team_name);
$query->execute();
print_r($query->errorInfo());
print $this->pdo->lastInsertID();
$new_id = $this->pdo->lastInsertID();
return $new_id;
}
Here's the code I've tried from the OTHER FILE:
sw::shared()->youth_teams->addTeam (
$team_name,
$error
);
$temp_two = sw::shared()->youth_teams->addTeam->pdo->lastInsertID();
echo "new id: " . $temp_two . "<br>";
Of course that is not working... What's the correct path to access $new_id?

It should be:
$temp_two = sw::shared()->youth_teams->addTeam($team, $error);
addTeam() is a function that returns $new_id, so you need to call it with ().
If you really want to be able to access $new_id directly, you can declare it global:
public function addTeam(
$team_name,
&$error
) {
global $new_id;
...

What was wrong with this?
$sw = new sw();
$temp_two = $sw->addTeam( $team, $error );
echo "new id: " . $temp_two . "<br>";
If you can call sw::shared() from the outside file, you can assign the object.
I probably am not fully understanding your code, if not, please fully explain the following:
sw::shared()->youth_teams->addTeam( $team, $error );
// 1. What does the shared() method do?
// 2. What is the youth_teams property?
If it's needed, might I suggest adding the assignment directly into the addTeam() function and use the above format to return the id only.

Related

System of logs for my site

I create a small class for save the logs of my website. My log class :
class Logs {
public static function writeFile($message)
{
$log_path = '/home/vagrant/Workspace/symfony/app/logs';
// Set path:
$log_path .= '/' . date('Ymd');
$log_path .= '.log';
$s_message = date("Y-m-d H:i:s") . ' (' . microtime(true) . ') ' . $message;
$s_message .= "\n";
file_put_contents($log_path, $s_message, FILE_APPEND);
}
public static function logInfo($s_message)
{
self::writeFile($s_message);
}
}
And I call the static method in my controller :
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$categories = $em->getRepository('EnsJobeetBundle:Category')->getWithJobs();
$test = array(
'1'=>'1',
'2'=>'2',
'3'=>'3'
);
Logs::logInfo(print_r($test));
return $this->render('EnsJobeetBundle:Job:index.html.twig', array(
'categories' => $categories
));
}
The problem is that : in my view it's show this $test array and in my log is write only the first value of array, so the value 1.
What I'm doing wrong? Help me please! Thx in advance!
In accordion with the doc:
If you would like to capture the output of print_r(), use the return
parameter. When this parameter is set to TRUE, print_r() will return
the information rather than print it.
Use this:
Logs::logInfo(print_r($test, true));
instead of:
Logs::logInfo(print_r($test));
hope this help
I suggest you to use Monolog for this task
http://symfony.com/doc/current/cookbook/logging/monolog.html
print_r has second parameter: return. Wich means will print_r() returns it's output, or just display it. It's false by default
So you need to try
Logs::logInfo(print_r($test,true));

Bind outside variable and in Class protected field with method param

How to implement this kind of functionality:
Fill entity eg. Member with data
Bind Member to form with $form->bind($member) to private property _formData
Afterward do some stuff inside $form, eg. $form->validate() with _formData
$member should be also changed as _formData is changed.
class Form {
private $_formData;
function bind1(&$row) {
// this change member outside
$row['full_name'] =
$row['first_name']
. ' ' .
$row['last_name'];
}
function bind2(&$row) {
$this->_formData = $row;
// this will not change memeber
$this->_formData['full_name'] =
$this->_formData['first_name']
. ' '
. $this->_formData['last_name'];
}
}
$member = array('full_name' => null, 'first_name'=>'Fn', 'last_name' => 'Ln');
$form = new Form();
$form->bind1($member);
var_dump($member['full_name']);
// output: 'FnLn'
$form->bind2($member);
var_dump($member['full_name']);
// output: null
Method validate work with private _fieldData, so this to work bind2 test should work.
What you are trying to do is possible, but you need to set a reference of the reference in the bind1 and bind2 method, like this:
$this->_formData = & $row;
You are also making misspellings between full_name and fullName as array keys. For example in the bind2 method:
$this->_formData['full_name'] = $this->_formData['first_name'] . ' ' . $this->_formData['last_name'];
And in your test-code you var_dump full_name. Chaging full_name in bind2 to fullName should fix your issue.
the problem is you are assigning the full_name key of your member variable and trying to access fullName variable so it is returning NULL

Return multiple values from a method in a class

I am trying to return multiple variables from a method.
This is what I have tried so far:
This code is the method in the class:
public function getUserInfo(){
$stmt = $this->dbh->prepare("SELECT user_id FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['username']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
$thumb = $row['thumbnail'];
}
return array($user_id, $thumb);
}
I attempt to place each variable in a list for use in the calling program:
session_start();
require_once('init.php');
$username = trim($_POST['username']);
// create a new object
$login = new Auth($_POST, $dbh);
if($login->validateLogin()){
$_SESSION['loggedin'] = true;
list($user_id, $thumb) = $login->getUserInfo($user_id, $thumb);
echo $user_id . ' ' . $thumb;
}
This hasn't work.
How can I return an array of multiple variables from a method within a class for use in the calling program?
The method that you define in the class doesn't match what you are calling.
// In the class, you have:
getUserInfo();
// But you call this:
getUserInfo($user_id, $thumb);
Because of this, PHP thinks you are calling a different method, and thus returns nothing (at least nothing of use here).
Your call should look like this:
list($user_id, $thumb) = $login->getUserInfo(); //Note that there are no parameters.
Another Option
Something else you should look at is using an associative array. It would look something like this:
//In the class:
public function getUserInfo() {
...
return array(
'id' => $user_id,
'thumb' => $thumb
);
}
//And then for your call:
$user = $login->getUserInfo();
echo $user['id'].' '.$user['thumb'];
This would be my preference when coding something like this, as I prefer having an array for related things, as opposed to a set of independent variables. But that is all preference.
This is similar to this question- PHP: Is it possible to return multiple values from a function?
you can also take a look here. where they explain about ways to return multiple values - http://php.net/manual/en/functions.returning-values.php
One thing that I noticed is that in this line
list($user_id, $thumb) = $login->getUserInfo($user_id, $thumb);
You are passing 2 parameters here but in the function definition part you don't have parameters -
public function getUserInfo(){
.....
}
public function getUserInfo(){
$stmt = $this->dbh->prepare("SELECT user_id FROM oopforum_users WHERE username = ?");
$stmt->bindParam(1, $this->post_data['username']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$user_id = $row['user_id'];
$thumb = $row['thumbnail'];
$return[] = array($user_id, $thumb);
}
return $return;
}
You could create a class, e.g., UserInfo, specifically for holding user information and return that.
You could also return an associative array, e.g...
$userInfo = array(
'id' => ...,
'thumb' => ...
);
A third alternative is to use references, but in this context I recommend staying away from that.

using query results in the same function that calls them

For some reason I am unable to use query results in the same function that calls them. Please see controller below and model and let me know where my issue is.
What breaks down is line 2 of controller, trying to concatenate query result contact_name and description_computer and saving it as variable name. I get the following error "Undefined variable: query" for both query results.
Using codeigniter.
Controller
function get_quarter_info($data)
{
$data['query'] = $this->model->get_client_info($data);
$data['name'] = $query['contact_name'] . " " . $query['description_computer'] . ".pdf";
$html = $this->load->view('Quarter_info_view', $data, true);
$pdf = pdf_create($html, '', false);
write_file($data['name'], $pdf);
$this->index();
}
Model
function get_client_info($data)
{
$query = $this->db->get_where('subscriber_report', array('client_number'=> $data['client_number']));
return $query->row_array();
}
You should probably use $query instead of $data['query]. The data array is used to pass data to your view.
You're not assigning a value to $query in get_quater_info. Instead, you're assigning the value to $data['query'];
Try this instead:
$query = $data['query'] = $this->model->get_client_info($data);

PHP getter method question

Hi Im new to PHP so forgive the basic nature of this question.
I have a class: "CustomerInfo.php" which Im including in another class. Then I am trying to set a variable of CustomerInfo object with the defined setter method and Im trying to echo that variable using the getter method. Problem is the getter is not working. But if I directly access the variable I can echo the value. Im confused....
<?php
class CustomerInfo
{
public $cust_AptNum;
public function _construct()
{
echo"Creating new CustomerInfo instance<br/>";
$this->cust_AptNum = "";
}
public function setAptNum($apt_num)
{
$this->cust_AptNum = $apt_num;
}
public function getAptNum()
{
return $this->cust_AptNum;
}
}
?>
<?php
include ('CustomerInfo.php');
$CustomerInfoObj = new CustomerInfo();
$CustomerInfoObj->setAptNum("22");
//The line below doesn't output anything
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
//This line outputs the value that was set
echo "CustomerAptNo = $CustomerInfoObj->cust_AptNum<br/>";
?>
Try
echo 'CustomerAptNo = ' . $CustomerInfoObj->getAptNum() . '<br/>';
Or you will need to place the method call with in a "Complex (curly) syntax"
echo "CustomerAptNo = {$CustomerInfoObj->getAptNum()} <br/>";
As your calling a method, not a variable with in double quotes.
for concat string and variables, you can use sprintf method for better perfomace of you app
instead of this:
echo "CustomerAptNo = $CustomerInfoObj->getAptNum()<br/>";
do this:
echo sprintf("CustomerAptNo = %s <br />", $CustomerInfoObj->getAptNum());
check http://php.net/sprintf for more details

Categories