I am have an instance variable w/ a global scope set in a PHP class. The variable gets set successfully in the constructor. But when I got to access in a getter method I get a PHP fatal error. I'm fairly new to php. Why is $sid not getting set?
class Wrapper
{
private $sid = null;
/**
public function __construct($data){
// Retrieve client account automatically
$sid = (isset($data['client_id'])) ? $data['client_id'] : null;
echo("set sid to");
echo($sid);
$this->client = new Account($sid); //this is getting set properly
}
...
public function getSID()
{
return $this->$sid;
}
The code that uses the class looks like this (it is a unit test with PHPunit):
public function testGetSubsctions(){
$clientObject = ClientModel::getInstance(7)->read();
$data = array('client_id' => $clientObject->id);
$this->assertEquals($data['client_id'], 7);
$hello = new Wrapper($data);
$this->assertEquals(7, $hello->getSid());
}
The code above throws the following error:
Cannot access empty property in /path to/wrapper.php on line 243
The code on line 242 is getSid, below
public function getSID()
{
return $this->$sid;
}
in the first part of the code you show, we can see return $this->$sid; but $sid is not defined. non-static property has to be called without the $
The correct syntax is :
public function getSID()
{
return $this->sid;
}
EDIT: see the php documentation for more help on the usage of $this->, static and other things related to OOP in php, and more specifically :
About properties
about static keyword (just for your information to see the difference)
Here is how you set $sid;
public function __construct($data){
// Retrieve client account automatically
$this->sid = (isset($data['client_id'])) ? $data['client_id'] : null;
echo("set sid to");
echo($this->sid);
$this->client = new Account($this->sid); //this is getting set properly
}
The variable is part of the instance so you have to use the $this keyword. Simply using $sid refers to a new local variable.
And also there is no $ sign before sid:
public function getSID()
{
return $this->sid;
}
Related
Here's the code (didn't include namespaces, routing):
class OneController extends Controller{
public $variable = "whatever";
public function changeVariableAction(){
$this->variable = "whenever";
// any code...
$this->redirectToRoute("class_two_route_name");
}
}
use AppBundle\Controller\OneController;
class Two{
public function otherFunctionAction(){
$reference = new One();
return new Response($reference->variable);
}
}
Why do I see "whatever" instead "whenever"? I know there is no line in the code executing changeVariableAction() but it is being executed when sb enters the route matching this action in class One ???
EDIT:
When I write the scheme outside SF3 I'm OK.
class One{
public $variable = "whatever";
public function changeVariable(){
$this->variable = "whenever";
}
}
class Two{
public function otherFunction(){
$reference = new One();
$reference->changeVariable();
echo $reference->variable;
}
}
$reference2 = new Two();
$reference2->otherFunction();
You are seeing "Whatever" instead of "Whenever" because of this line:
new One();
By calling "new One();" you are creating a new instance of the class "OneController" thus, it will set its default value "whatever" as the function "changeVariableAction" is not being called in your new instance $reference.
After research I can see that in SF (as it is a framework) we don't treat Action functions as typical functions (it's sth about http etc.) so we cannot execute them in another class. What's more, the whole code inside Action function doesn't influence the code outside the Action function. The only way to get new property value is to send them via argument in url (I don't think we want that) or send to db and retrieve it from database in another class.
Here's the proof:
class FirstController extends Controller{
public $variable = "whatever";
/**
* #Route("/page")
*/
public function firstAction(){
$this->variable = "whenever";
return $this->redirectToRoute("path");
}
}
class SecondController{
/**
* #Route("/page/page2", name = "path")
*/
public function secondAction(){
$reference = new FirstController();
$reference->firstAction();
return new Response($reference->variable);
}
}
This code gives an error: Call to a member function get() on null.
When I delete line $reference->firstAction(); there is no error and "whatever" shows up (so the original).
I basically know php but i am new to all that classes-stuff. For now - love it.
Here is my problem:
I'm writing a class to do all that stuff around the account-managements. (e.g. create new account, get account details, check if account exists .... )
Within that class i need to do some MySQL-requests. Therefor i i'm using the medoo-class (http://www.medoo.in).
class acc{
// Attributes
public static $account;
public $pw;
protected $error;
public function acc_exist() {
$database = new medoo();
$acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);
if ($acc_count == 0) {return true;} else {$this->error .= "Account exists already!";};
}};
Please note the line:
$database = new medoo();
and
$acc_count = $database->count("table_accounts", ["column_account" => acc::$account]);
here i bring in medoo. And ["column_account" => acc::$account] acctually works. As i read in some other posts, i made $accounts public static.
now i call my class like this:
$my_acc = new acc();
$my_acc->account = 'Luci';
$my_acc->acc_exist();
i need to work like that. Doing some acc($account) is difficult in context of the rest of my code.
But as i expected, i get an error:
Strict Standards: Accessing static property acc::$account as non static
clear to my that static holds the var's value. so i will need some other way. Anyone got an idea?
best, Lox
I don't think you need to have $account as static, that wouldn't make sense with the way you're probably going to be using this code, try having public $account; and then use ["column_account" => $this->account]
So:
class acc{
// Attributes
public $account;
public $pw;
protected $error;
public function acc_exist() {
$database = new medoo();
$acc_count = $database->count("table_accounts", ["column_account" => $this->account]);
if ($acc_count == 0) {return true;} else {$this->error .= "Account exists already!";};
}};
Here's more information on how to use static properly: Static Keyword in PHP
You are calling a variable that doesn't exist.
You declared $accout as public and static.
But you attempt calling $account.
Replace:
$my_acc->account = 'Luci';
With:
$my_acc->accout = 'Luci';
Vex is right. Take off the static keyword and use ["column_account" => $this->account] instead.
Bests,
B.
I am wondering is it possible for me to access the _staff_id variable without me having to change the declaration to public (I have access to change this but its not my code and im assuming it was made private for a reason, however i am still tasked with getting this information)
MyObject Object
(
[_staff_id:private] => 43
)
Using a public get function. E.g.:
class MyObject {
private _staff_id = 43
public function get($field) {
return $this->$field;
}
}
$myObject = new MyObject;
$staff_id = $myObject->get('_staff_id');
This allows you to access the variable without the ability to overwrite its value.
I have a static method that returns or creates an object if it doesn't exist. I'd like to find an elegant way to handle passing an ID argument to the object.
The logic here is that if an ID is passed, the object is created with that ID. If not, it's created with a default ID.
What I had was:
class App {
private $game_obj;
public static function get_game ($arguments) {
if (!isset($this->game_obj))
$this->game_obj = new Game ($arguments[0]);
return $this->game_obj;
}
}
class Game {
private $gameID;
public function __construct ($id=1) {
$this=>gameID = $id;
/* other code */
}
}
When I call App::get_game(5) I get the result I expect. A Game object with a gameID of 5.
When I call App::get_game() I do not get the result I expect, which would be a Game object with a gameID of 1. Instead I get an error about undefined offset in the App::get_game ().
I updated App::get_game() as follows, but it seems particularly inelegant. I'd prefer to define the default ID in the class definition.
class App {
private $game_obj;
public static function get_game ($arguments) {
if (!isset($this->game_obj)) {
$default_id = 1; // I don't like having this here
$id = isset ($arguments[0] ? $arguments[0] : $default_id;
$this->game_obj = new Game ($id);
}
return $this->game_obj;
}
}
Is there a simpler/better/more elegant way to handle this? Ideally one that would keep my default ID declaration in the Game class itself?
did you try
public static function get_game ($arguments=null) {
if($arguments==null) //etc..
?
you can test with :
if(is_object($my_object)) {
}
I am currently working on a large project for a client, and to help simplify things and make managing sessions easier I have made a session class, this means that if I ever change the way I manage my sessions I can access the structure of the sessions in one file rather then multiple files where a session has been echoed (Such as the users name or the current page)
My class has 3 types of functions setters, getters and unsetters which is kind of self explanatory.
Now in this instance I am setting an error message to the session class directly and then getting the error messages from another class which calls a function from the session within it.
Below are simplified versions on my files showing code I feel is relevent
c_session.php
class session {
private $instance = 'isntname';
private $A_user = 'user';
private $A_page = 'page';
private $A_message = 'message';
//Set messages to the session.
public function set_message($type, $value) {
$_SESSION[$this->instance][$this->A_message][$type] = $value;
}
//Get messages from the session.
public function get_message() {
return $_SESSION[$this->instance][$this->A_message];
}
//Unset messages from the session.
public function unset_message() {
#unset($_SESSION[$this->instance][$this->A_message]);
}
}
c_operations.php
class operations {
//Display all pending messages.
public function display_pending_messages() {
if(session::get_message() != null) {
foreach(session::get_message() as $type => $value) {
if(strlen($type) != null) {
echo '
<div class="panel ' . $type . '">
' . $value . '
<span class="close" onclick="hide_parent_element(this);">X</span>
</div>
';
}
}
session::unset_message();
}
}
}
example.php
$session->set_message('confirm', 'THIS IS A CONFIRM');
$session->set_message('error', 'THIS IS AN ERROR');
$session->set_message('notice', 'THIS IS A NOTICE');
$session->set_message('warning', 'THIS IS A WARNING');
var_dump($_SESSION);
$operation->display_pending_messages();
Errors/notices etc received
Notice: Undefined property: operations::$instance in /var/www/_classes/parent_session.php on line 43
Notice: Undefined property: operations::$A_message in /var/www/_classes/parent_session.php on line 43
Notice: Undefined index: in /var/www/_classes/parent_session.php on line 43
Line 43 refers to the line return $_SESSION[$this->instance][$this->A_message];
Now if I call get_message() and unset_message() directly via $session->get_message() it works as expected but going through another function in this case $operation->display_pending_messages() it returns the above errors. Obviously this has something to do with the $this-> operator but I'm not to sure on what to do to stop this. I have tried various searches and while finding something similar it wasn't helpful in this case.
Can someone please explain where I've gone wrong and how to fix this?
Thanks in advance.
In class operations you call your session as static but all your data is in an object.
The best way is to store in a static, all data of your class session :
`
class session {
private static $instance = 'isntname';
private static $A_user = 'user';
private static $A_page = 'page';
private static $A_message = 'message';
//Set messages to the session.
public static function set_message($type, $value) {
$_SESSION[self::instance][self::A_message][$type] = $value;
}
//Get messages from the session.
public static function get_message() {
return $_SESSION[self::instance][self::A_message];
}
}
And so you can call all your functions with session:: in your code, without create object session
You are trying to call these functions statically, but they are instance methods. e.g session::get_message() Try either adding the static keyword to the functions or better still pass in instantiated class and call the methods with $session->get_message()
public function display_pending_messages($session) {
if($session->get_message() != null) {
etc.