I am trying to understand how classes and functions work more.
So i have written a class with 2 functions inside it. Then initiated the class with
$fifaadmin = new FifaAdmin;
When I try to call this class from another page i get the following error
Call to a member function leagueToReplace() on a non-object
What am i doing wrong? Is there an obvious answer?
Thanks
You need to instantiate the class on each page. Each script is executed independently.
Sounds like $fifaadmin didn't instantiate the object correctly.
What does this say?
var_dump($fifaadmin instanceof FifaAdmin);
It should return true if it is set up correctly. Try it just before you call a method on it.
When you say another page, do you mean from a PHP include or a new URL (and therefore request)?
You will need to instantiate it on every request, as HTTP is stateless.
Depending on what your code does, you might want to use static methods:
// common.php
class Common {
public static function calculate($x, $y) {
return $x + $y;
}
}
// another PHP file: (you still need to include common.php
// you won't need to instantiate the class
echo Common::calculate(10, 20);
If you want to use an instance of class in different pages, you need to serialize it and save it somewhere (session is ok) and de-serialize it when you want use it.
More detail about serialize in PHP here http://php.net/manual/en/function.serialize.php
Related
I have a need to call a class which will perform actions but which I know I will not be calling the methods of. This is a PHP application. Does anyone ever just do the following:
require('class.Monkeys.php');
new Monkeys(); //note I didn't assign it to a variable
Yes, that's perfectly valid. However, it is arguably bad form, because the golden rule is that:
Constructors should not do actual work.
A constructor should set up an object so that it is valid and in a "ready state". The constructor should not start to perform work on its own. As such, this would be saner:
$monkeys = new Monkeys;
$monkeys->goWild();
Or, if you prefer and are running a sufficiently advanced PHP version:
(new Monkeys)->goWild();
Well let just say that we have a classname called Monkeys.
File class.Monkeys.php
class Monkeys {
function __construct()
{
$this->doSomething()
}
public function doSomething(){
echo "new Monkeys()->doSomething() was called";
}
public function anotherMethod(){
echo "new Monkeys()->anotherMethod() was called";
}
}
Now you can instantiate the class on runtime without saving it into a variable.
require('class.Monkeys.php');
// you can just instantiate it and the constructur will be called automatically
(new Monkeys());
// or you can instantiate it and call other methods
(new Monkeys())->anotherMethod();
I'm not sure if the garbage collector will delete the instantiated classes or not, but i assume since those classes are not saved into a variable this would not be saved somewhere in the memory and that would be perfect.
Just wondering if there is any way to dump and view the function/method definition inside the class using the Object name?
I found the way to get the class name and method name as well using an instantiated object name with this function:
public function getObjectMethods(object $obj) {
$className = get_class($obj);
//return $className;
return get_class_methods($className);
}
Also, I could access the properties in the class by using the var_dump; however, is there any way I could see the method/function definition inside the class?
Well AFAIK, there is no such function to see what code written on the function directly. (well, you can get the function line number and read the file with file_get_contents)
You could use Kint as a temporary option. It's uses reflection to deep dive into the class/object/instance.
https://github.com/kint-php/kint
Kint::dump($obj);
update:
the code i put below will be invoked by a form on other webpage. so that's why I didn't made a instance of a obj.
More detail code:
$serverloc='serverURL';
class Aclass{
function push(){
global $serverloc;
echo $serverloc;
funNotinClass();
}
function otherFunction(){
echo $serverloc;
}
}
funNotinClass(){
echo $serverloc;
}
There is a Class contains 2 functiona "push()" and "otherFunction()" and there is independent function "funNotinClass()" and push() calls it. The class is for a web form in other page. When user click submit the form call the class and use the push() function. A weird thing I found is that the global var $serverloc is invisible to push() and funNotinClass()(they don't print out any thing), but otherFuction() which is a function just like puch() inside of the Aclass can just use the $serverloc(I dont even add global in front of it). How strange....anyone know what is the reason caused this?
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
I read many information about the scope of a global var in php.
they all say a global var is defined outside of function or class and you can use it by using global this key word.
So this is my code
$serverloc='serverURL';
class Aclass{
function Afunction(){
global $serverloc;
echo $serverloc;
}
}
but when I run this class it didn't print anything out.
Is that because I did something wrong or global var just doesn't work this way. Since all the example I read before are just access a global var in functions directly not a function in a class
As per DaveRandom's comment - you haven't actually made an instance of an Aclass object.
This works and displays data as expected:
<?php
$serverloc='serverURL';
class Aclass{
global $serverloc;
function Afunction()
{
echo $serverloc;
}
}
$me = new Aclass();
$me->Afunction(); // output: serverURL
?>
Edit: DaveRandom seems to post asnwers as comments. Go Vote up some of his other answers, the rep belongs to him not me. I am his ghostwriter tonight.
If it is class globals you are after you could do like
class myClass
{
private $globVar = "myvariable";
function myClass()
{
return $this->globVar;
}
}
but when I run this class it didn't print anything out
You don't run classes, in the sense of executing them. A class is a just a data structure that holds data and functions related (called methods).
As most traditional data structures, you create instances of them (called objects), and then you execute actions on them. One way to execute actions on objects (instances of classes), is to pass a message for it to do something: that is calling a method.
So, in your case you could do:
$obj = new Aclass(); // create an object, instance of Aclass
$obj->Afunction(); // ask it to perform an action (call a method)
Having said that, sometimes you want to create a class only for grouping related functions, that never actually really share data within an object. Often they may share data through a global variable (eg.: $_SERVER, $_GET, etc). That may be the case of your design right there.
Such classes can have its methods executed without never instantiating them, like this:
Aclass::Afunction();
While relying on global variables is usually an indicator of quick'n dirty design, there are cases in which it really is the best trade-off. I'd say that a $serverlocation or $baseurl may very well be one of these cases. :)
See more:
The basics on classes and objects in the PHP manual
About the static keyword
i have included a file in another file and now i want to use on of the functions from the included file.
when i go to the included file and put a variable there the variable get passed and its all good
- that means i have includedd the right file.
but when i want to call a funcion which is inside a class
class SimpleViewer {
.
.
.
.
function whatever(){}
it just doesnt call it when i each it and writes
Fatal error: Call to undefined function display_gallery_table()...
i know for sure im in the right file because the other values passed but i just can call nothing because its insidfe the class
what am i doing wrong?
Try initiating an instance of the class first like this
$myClass = new SimpleViewer();
then call the function like this
$myClass->whatever();
$var = new SimpleViewer();
$var->whatever();
You need to create an instance of the object first;
$obj = new Class();
$obj->func();
There are many ways to call a function between classes. The first I know is a static method call. You can call function by defining class::function().
example :
public class Parent{
public static function check(){
....
....
}
}
the static caller may look alike
Parent::check()
Second way is initiate the class as the new object. From the example we can do the call like
$obj = new Parent;
$obj->check();
the rest manual of implementing this is on php manual
like this:
if ($sth) make_private($this->method);
or maybe there's some other way to affect accessibility of methods ?
Problem is that I written a class where methods must be called once, so I need code to restrict access to given method from outside the class after this method was executed.
You've got several better options:
Handle the 'can only be called once' with some static state variable in the class itself, and throw legible exceptions.
Handle the 'can only be called once' with a decorator object if you cannot alter the class/object itself.
The very undesirable way you suggest is possible, see classkit_method_redefine or runkit_method_redefine, but on behalf of anyone possibly working on your code in future: please do not use it.
Simple way to do so within the mothod (restrict to one call):
public function fooBar() {
static $called;
if (isset($called)) throw new Exception('Called already once!');
$called = true;
// your code
}