I have read all related question, but failed to remove the bug from my code. Please guide me about possible error in my code.
When I try to call following code, it reports Error: Call to undefined method SessionManager::close() in E:\wamp64\www\mjs-cms\private\systemcore\helper\SessionManager.php on line 22 instead of "tried to call close".
Thanks in advance.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class SessionManager{
public function __construct() {
session_start();
}
public function is_exist($a){
return isset($_SESSION["system".$a]);
}
public function add($a,$b){
$_SESSION["system".$a]=$b;
}
public function addCookies($a,$b){
setcookie($a, $b, time() + (86400 * 30), "/"); // 86400 = 1 day
}
public function sessionKey(){
return session_id();
}
public function value($k){
if(!isset($_SESSION[$k]))
$this->close("SESSION_NOT_DEFINED".__LINE__);
return $_SESSION[$k];
}
public function __get($key)
{
echo "tried to call $key";
return get_instance()->$key;
}
}
__get method is for accessing undeclared properties of a class.
For calling undeclared functions is __call or __callStatic.
public function __call($method_name, $arguments)
{
echo "tried to call: $method_name";
}
If you want to use __get - you must call for undefined property. In this case it is not
SessionManager::close() // call method `close()`
It must be:
$sm = new SessionManager;
$sm->propertyName; // trying to access undefined property `propertyName` of an object
Take into consideration that
Property overloading only works in object context.
which means that trying to access static property like
SessionManager::staticProperty;
will not work with __get.
Related
I have defined static variable in controller but when I use that variable in functions it is giving undefined variable error.
Controller
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends Admin_Controller {
private static $secure_key = "aXXXXXXXXc";
public function __construct()
{
parent::__construct();
}
public function edit($id)
{
try
{
$token = JWT::encode($postdata, $secure_key);
echo "<pre>";print_r($token);exit;
}
catch(Exception $e){
$this->data['error'] = $e->getMessage();
redirect('/','refresh');
}
}
}
$token gets printed properly with jwt but I am getting an error
Undefined variable: secure_key
I tried different methods to define $secure_key as
public static $secure_key = "aXXXXXXXc;
static $secure_key = "aXXXXXXXc;
I tried to define $secure_key in constructor also as
$secure_key = "aXXXXXXXc;
but no use. Why so? Please help. I am using codeigniter 3
Recommended Method (Based on Security)
Define variables in config.php and access it. This will work like Global Variable
$config['secure_key'] = 'myKey';
$this->config->item('secure_key'); # get
$this->config->set_item('secure_key', 'NewKey'); # set
Access it like this
$this->$secure_key
As per Comment by cd001
self::$secure_key
If function
$this->function_name();
Since $secure_key is declared as static inside your class. So it can be accessed using self or className as
self::$secure_key
or
Quiz::$secure_key
I am using Symfony 1.0, and I have this MyClassInc.class.php in my project/lib folder
class MyClassInc {
public function validateFunction ($params) {
// my codes
}
static function testFunction ($params){
// my codes
}
}
Then, my action actions.class.php in my project/apps/myapps/modules/actions.
class inventoryCycleCountActions extends sfActions
{
public function validateOutstandingTransaction () {
$res0 = MyClassInc :: validateFunction($param); // It works
$res1 = MyClassInc :: testFunction($param); // It works
$myClass = new MyClassInc();
$res2 = $myClass->validateFunction($param); // still works
$res3 = $myClass->testFunction($param); // still works, da hell?
}
}
I tried to clear my cache folder to do re-test, but it seems that all of those work just fine.
Question:
So.. WHY? and which one should I use? Does it have any effect with performance or anything?
Update 1:
class MyClassInc {
public function isProductValidated ($product){
return true;
}
public function validateFunction ($params) {
// IF, I call by using "$res0".. Throws error
//
$this->isProductInLoadPlans($product);
}
}
If I call validateFunction via $res0, it will throw this error:
sfException: Call to undefined method
inventoryCycleCountActions::isProductValidated.
And, if I call it via $res2, it works just fine.
Since, I am currently using $res0 and so I have to call that method like this instead.
MyClassInc :: isProductValidated ($product)
The only real difference between :: and -> is how $this is handled. With :: the function will have $this as it was defined in the caller's scope:
class A {
public function foo() {
A::bar();
A::foobar();
}
static private function bar() {
// $this here is the instance of A
}
static public function foobar() {
// Here you can have anything in $this (including NULL)
}
}
$a = new A;
$a->foo();
$a->foobar(); // $this == $a but bad style
A::foobar(); // $this == NULL
When you want to use an instance method, you should use -> because that would resolve instance methods properly (including inheritance). :: will always call the method of the specified class.
I believe there is effort made now to enforce calling static methods only as statically and dynamic methods only dynamically to avoid the confusion.
Here's my test:
<?php
require __DIR__ . '/vendor/autoload.php';
class HasStatic {
public static function static_method() {
return true;
}
}
class SUT {
public $has_static;
public function __construct() {
$this->has_static = new HasStatic();
}
public function call_static() {
// A parse error :<
// $this->has_static::static_method();
$has_static = $this->has_static;
return $has_static::static_method();
}
}
class PhpStaticCallOnProperty extends PHPUnit_Framework_TestCase {
public function testPhpStaticCallOnProperty() {
$sut = new SUT();
$this->assertTrue($sut->call_static(), 'call_static() succeeded');
}
}
As you can see, I discovered that $this->has_static::static_method(); yields a parse error.
Is there a clean way to make this call without the extra assignment?
Static methods are black boxes of functionality where you explicitly define everything going in (parameters) and out (return value). As such, they are not tied to an object - and you shouldn't call them using an object reference. static_method() should only ever be called using HasStatic::static_method(), or self::static_method() from within the HasStatic class.
There's nothing inherently wrong with static methods - I strongly disagree with tereško saying they should be avoided. If a method doesn't need an object's context, it may as well be static.
The parse error occurs because there's no reason to use the scope resolution operator (::) on a property. Variable class names do mean the following will work:
$foo = 'HasStatic';
$foo::static_method(); // equivalent to HasStatic::static_method()
However that variable cannot be a property - you'll have to assign it to a temporary variable if you want to call the method in this way.
I have a class like this:
// file /models/person.php
class Person
{
public function create_path()
{
self::log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
This is the way how Person is instanciated:
//file /tools/Builder.php
include('/models/Person.php');
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
As you note in Person class, I am calling the object in question with $this reference. But this is not correct because an error is showed:
Message: Undefined variable: this
I suppose that $this reference point to other object or it is unable to work because the object is created from another script. Also, I tried to use self because there was not problem calling methods with that, but as parameter I get:
Message: Use of undefined constant self - assumed 'self'
So, can you guide me to the right direction?
I tested your code out for myself, with a few minor changes. It appears to work properly.
Changed self::log() to $this->log()
Added global function path_helper (I have no idea what this does)
PHP
function path_helper(Person $object)
{
var_dump($object);
}
class Person
{
public function create_path()
{
$this->log();
path_helper($this); //a global function in other php file
}
public function log()
{
echo "trying to create a path";
}
}
class Builder
{
public function build()
{
$type = 'Person';
$temp = new $type();
$temp->create_path();
}
}
$Build = new Builder();
$Build->build();
Result
trying to create a path
object(Person)[2]
Your code is correct and your going in the right direction.
You should call the log method like this:
$this->log();
because using self:: is reserved for static methods.
Also, try calling the path_helper function like this:
path_helper(self);
Hope I could help you. Couldn't test it, but it should work.
All,
I'm getting an error with the code below. Here is the error message I get:
Notice: Undefined variable: userDAO in C:\wamp\www\Projetv0.2\Model_User.php on line 15
and then
Fatal error: Call to a member function checkRecordExists() on a non-object in C:\wamp\www\Projetv0.2\Model_User.php on line 15
The relevant code is below. What I try to do with the code is have a unique class (DAO_DBrecord) to access several tables in a db. In the case below, I want to access my users table. To do that I have created a specific static function createUserDAO inside the DAO_DBrecord class that calls the constructor with the right table name, users. However, it doesn't work, and I can't figure why.
Model_User.php:
<?php
require_once('Class_DB.php');
require_once('DAO_DBrecord.php');
class Model_user{ // Represents a connection to the users table in the DB
private $db;
private $userDAO;
function __construct($db){
$this->db=$db;
$userDAO=DAO_DBrecord::createUserDAO($this->db);// static function - calls constructor w/ 'user' table name parameter
$this->userDAO=$userDAO;
}
function userInfoExists($userInfo, $colName){
return $userDAO->checkRecordExists($userInfo, $colName);
}
//Other stuff
}
?>
DAO_DBrecord.php:
<?php
require_once('Class_DB.php');
class DAO_DBrecord {
private $db;
private $table;
private function __construct($db,$table){
$this->db=$db;
$this->table=$table;
}
public static function createUserDAO($db) {
return new DAO_DBrecord($db, 'users');
}
//Other stuff
}
?>
Thank you all for your help!
JDelage
That's not a problem with the static function. The problem is that PHP doesn't have an implicit $this. When you're referring to the member variable within the class (as you are in userInfoExists), you have to say $this->userDAO rather than just $userDAO.
Of course, all this assumes that the DAO_DBrecord class has or inherits a checkRecordExists function. If it doesn't, you're going to have other problems.