PHP Using $this->load Fatal Error - php

Cant seem to wrap my head around $this!
I am trying to emulate a codeigniter function of loading views but i am obviously missing something.
class Load{
public function __construct(){
}
public function view(){
echo "Hello";
}
public function files(){
}
public function plugins(){
}
}
$this->load->view();
This throws the following
Fatal error: Using $this when not in object context
However when i use:
$load = new Load;
$load->view();
I get the expected response. Hello
Why does it work in Codeigniter but not in my simple script?
Ive already googled and searched SO..

In your code you use $this not in a class. So it is really not an object.
You should create the object of class before use it.
Or if you want to use it in other class, just do something like that:
class PreLoad
{
public load;
public function __construct()
{
$this->load = new Load();
}
public function show()
{
$this->load->view();
}
}
(new PreLoad())->show();

Related

How to Invoke Object that's a Public Property

Take the following example of two classes:
class Yolo {
public function __invoke() {
echo 'YOLO';
}
}
class Swag {
public $yolo;
public function __construct() {
$this->yolo = new Yolo();
}
}
Is it possible to invoke the Yolo object via an instance of Swag?
(new Swag())->yolo(); throws a warning and doesn't call __invoke:
PHP Warning: Uncaught Error: Call to undefined method Swag::yolo()
In PHP 7 you can directly call it (just need extra braces):
((new Swag())->yolo)();
In PHP 5 you need a temp variable:
$y=(new Swag())->yolo;
$y();
The problem is that you try to call the function yolo() on the Swag class. In your case you have to use the public class variable and call the subclass over that.
var_dump((new Swag())->yolo);
that is your object. When you use () you try to call the class not the class variable.
You do not even have to make it a public method.
But you might have to reroute the call manually since the callable method is created at runtime:
class Yolo {
public function __invoke() {
echo 'YOLO';
}
}
class Swag {
private $yolo;
public function __construct() {
$this->yolo = new Yolo();
}
function __call($method, $args) {
if(is_callable($this->$method))
{
return call_user_func_array($this->$method, $args);
}
}
}
(new Swag())->yolo();
It would probably a good idea to check first, if the called method exists and if it is actually callable.
But the example works as a proof of concept.

codeigniter libraries dependancies

Im trying to pass objects between classes in code igniter and am currently failing. What am I doing wrong. Let me strt showing the pure.php version
Errors.php
<?php
class Errors
{
public function __construct(){}
public function setError($msg){}
}
OtherClass.php
<?php
class OtherClass
{
public function __construct(Errors $errorObject) {}
public function someMethod() {}
}
Then in my main controller..
Controller.php
<?php
class Main
{
public function __construct()
{
$this->errors = new Errors;
$this->other = new OtherClass($this->errors);
}
}
By doing this. I can add errors as I go to my error Object, across any objects i instantiate from the Main controller.
Now my code igniter version looks like this
/library/Errors.php
<?php
class Errors
{
public function __construct(){}
public function setError($msg){}
}
/library/OtherClass.php
<?php
class OtherClass
{
public function __construct(Errors $errorObject) {}
public function someMethod() {}
}
Then in my main controller..
Controller.php
<?php
class Main extends CI_Controller
{
public function __construct()
{
$this->load->library('Errors');
$this->load->library('OtherClass',$this->errors);
}
}
When I do this I get an error in my OtherClass saying that $errorObject is not an instance of Errors. Why is the object not being passed?
The problem is with $this->load->library which is defined like this.
public function library($library, $params = NULL, $object_name = NULL)
$params is expected to be an array. If it is not then the $params is set to NULL.
To get around this requires a bunch of monkey biz.
class Errors is unchanged but class OtherClass needs to be changed to...
class OtherClass
{
public function __construct($errorObject)
{
var_dump($errorObject[0]); //so we can prove it got passed
}
public function someMethod(){}
}
Note the removal of the type hint Error from the constructor declaration. Also, we access index 0 of the argument. The reason lies in what happens at the controller.
function __construct()
{
parent::__construct();
$this->load->library('Errors');
$this->load->library('OtherClass', [$this->errors]);
}
We have to put $this->error in an array so that load->library() won't mess with it.
The alternative is to not use "The CodeIgniter Way" and use good old fashion `new' instead. The controller then is...
function __construct()
{
parent::__construct();
$this->load->library('Errors');
$this->other = new OtherClass($this->errors);
}
And other class reverts to...
class OtherClass
{
public function __construct(Errors $errorObject)
{
var_dump($errorObject);
}
public function someMethod(){}
}
Now the problem is that without adding an autoloader to the system you wind up with
Fatal error: Class 'OtherClass' not found in ...
This LINK goes to a page that talks about the various ways to add an autoloader to CI. I know this has been answered on SO too. But I'm failing to find it at the moment.

Cannot set Parent property from child class

I have view class like this:
class View {
public function __construct() {
}
public static function render($name) {
require 'views/user/header.php';
require 'views/user/'.$name.'.php';
require 'views/user/footer.php';
}
}
and I call the view class in controller like this:
class Controller {
function __construct() {
$this->view = new View();
}
}
and then I set the view property from controller child class, like this:
class Index extends Controller {
function __construct() {
parent::__construct();
$this->view->js = "test";
}
public function index() {
$this->view->render('index/index');
}
}
But when I want to get $this->js from "header.php" which is set at render function on view class, I always get this error message:
Fatal error: Uncaught Error: Using $this when not in object context
I was tried to check, Am I in the right class? using this methods in "header.php" file:
echo get_class(); // and this method return "View";
that means I was on the view class, right?
Can anyone please help me?
Thanks in advance
You have defined render() as a static method, but you are calling it as it was not static.
I would probably benefit from reading this: http://chadminick.com/articles/simple-php-template-engine.html
P.S. What you call "view" is just a template.

Variables in __construct() when called by mysqli_fetch_object

I've got a class 'Event' which I am creating objects from via mysqli_fetch_object. The __construct() function is running and the objects variables are being set but they aren't set within the __construct() function.
I am using the following line to create the object:
$events[$x] = $result->fetch_object("Event")
When I run the following function by calling $events[$x]->eventPlaces(); it echos the variable.
public function eventPlaces()
{
echo $this->capacity;
}
However with the same code in the construct function it echos nothing.
public function __construct()
{
echo $capacity;
echo $this->capacity;
}
Apologies if I have explained this poorly, I've just got back into coding and OO php is new to me, if I missed anything then let me know.
I think you want your class to look like this:
class Event{
protected $capacity;
public __construct($capacity){
$this->capacity = $capacity;
}
public function eventPlaces(){
return $this->capacity;
}
}
Then you would do this:
$events[$x] = $result->fetch_object("Event", array(12));
echo $events[$x]->eventPlaces();

undefined function when function is present

I have a PHP class that looks like this:
class userAuthentication
{
public static function Authenticate()
{
if (isset($_COOKIE['email']))
{
verify($someVar, getPass($_COOKIE['email']);
}
}
public static function getPass($email)
{
}
public static function verify()
{
}
}
At times (I can't pin-point exactly when), I get a fatal error :
Call to undefined function getPass()
The error is thrown at the line where I call the function in the above code sample. Why is this happening when the function clearly exists.
It's a static function in a class. Use self::getPass() or static::getPass() if you want to take advantage of Late Static Binding. Same goes for verify().
verify is not a global function, but only valid in the scope of your class. You want
self::verify($someVar, getPass($_COOKIE['email']);
I would assume the error occurs when you try to run getPass($_COOKIE... since you're calling it wrong. Since the function is a class method, you have to run it like this:
$this->getPass(...);
or if you're calling it statically:
self::getPass(...);
Making your code:
class userAuthentication
{
public static function Authenticate()
{
if (isset($_COOKIE['email']))
{
self::verify($someVar, self::getPass($_COOKIE['email']);
// Or...
$this->verify($someVar, $this->getPass($_COOKIE['email']);
}
}
public static function getPass($email)
{
}
public static function verify()
{
}
}
You're not calling it as a static function.
From within the class use either:
self::getPass($email);
or (for late static binding):
static::getPass($email);
and from outside the class:
userAuthentication::getPass($email);
The line should probably be:
self::verify($someVar, self::getPass($_COOKIE['email']);

Categories