PHP call Class method / function - php

How can I call following Class method or function?
Let say I have this params get from url:
$var = filter($_GET['params']);
Class:
class Functions{
public function filter($data){
$data = trim(htmlentities(strip_tags($data)));
if(get_magic_quotes_gpc())
$data = stripslashes($data);
$data = mysql_real_escape_string($data);
return $data;
}
}
thanks.

To answer your question, the current method would be to create the object then call the method:
$functions = new Functions();
$var = $functions->filter($_GET['params']);
Another way would be to make the method static since the class has no private data to rely on:
public static function filter($data){
This can then be called like so:
$var = Functions::filter($_GET['params']);
Lastly, you do not need a class and can just have a file of functions which you include. So you remove the class Functions and the public in the method. This can then be called like you tried:
$var = filter($_GET['params']);

Within the class you can call function by using :
$this->filter();
Outside of the class
you have to create an object of a class
ex: $obj = new Functions();
$obj->filter($param);
for more about OOPs in php
this example:
class test {
public function newTest(){
$this->bigTest();// we don't need to create an object we can call simply using $this
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
$testObject = new test();
$testObject->newTest();
$testObject->scoreTest();
hope it will help!

Create object for the class and call, if you want to call it from other pages.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
Or inside the same class instances [ methods ], try this.
$var = $this->filter($_GET['params']);

$f = new Functions;
$var = $f->filter($_GET['params']);
Have a look at the PHP manual section on Object Oriented programming

As th function is not using $this at all, you can add a static keyword just after public and then call
Functions::filter($_GET['params']);
Avoiding the creation of an object just for one method call

You need to create Object for the class.
$obj = new Functions();
$var = $obj->filter($_GET['params']);

This way:
$instance = new Functions(); // create an instance (object) of functions class
$instance->filter($data); // now call it

Related

PHP: Create a new class object directly from a string return value (string literal)

Is there any possibility to create a new object by a string that is returned by a function or method in PHP? Like some escape method I do not know?
Non-working example:
new ($class->method())();
new "stringliteral"();
new ($class = $class->method())();
You can do it using ReflectionClass
function makeRef($className) {
return new ReflectionClass($className);
}
$obj = makeRef($class->method())->newInstance();
In PHP 5.4+ you can turn this into a one-liner:
$obj = (new ReflectionClass($class->method()))->newInstance();
Do you want dynamic class creation?
here is a read :
http://docstore.mik.ua/orelly/webprog/pcook/ch07_13.htm
While it is OK to invoke dynamic function, doing it for class seems to be a stunt.
Yes it is possible. Assign the string to a variable then create object using that variable.
Ex.
<?php
class stringliteral{
function __construct()
{
echo"called";
}
}
function dumyFunc()
{
return 'stringliteral';
}
$str=dumyFunc();
if(class_exists($str))
$obj=new $str();
?>

Using local variable from call in a function

After 9 hours of struggling to get this right, I have turned to the internet for help. I can't seem to find any relevant answers doing a Google search.
I currently have a class called Test. Test accepts a single argument.
<?php
class test {
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
The stringGen function should return the $varpassed variable whenever its called. The value for $varpassed is set using the setVarpas function. However, when ever I call the stringGen() method I only seem to be getting the following error:
Fatal error: Using $this when not in object context in file.php line 14.
Pointing to this line:
$testvar = $this->varpassed;
Is there any other way to pass the variable to the stringGen method? I've tried using:
self::$this->varpassed;
Which also throws an error.
first create an instance of the object (so you can use $this in the context), for example:
$test = new test();
then you can call:
$test->setVarpas('Hello World!');
now you can call:
$test->stringGen();
you have to do something like this
$var = new test();
$var->setVarpas("Hello");
$var->stringGen(); // this will echo Hello
$this is used when you are withing class. outside class you have to use class object.
1) Change this: class test() to class test
2) Create and instance first something like $t1 = new test();
3) Call the function $t1->setVarpas(5);
4) Now you can call the function $t1->stringGen();
Fixed:
<?php
class test
{
private $varpassed;
public function getVarpas() {
return $this->varpassed;
}
Public function setVarpas($value) {
$this->varpassed= $value;
}
public function stringGen(){
$testvar = $this->varpassed;
echo $testvar;
}
}
$t1 = new test();
$t1->setVarpas(5);
$t1->stringGen();
OUTPUT:
5
You should not declare a class with parentheses.
Use
class test {
instead of
class test(){

Storing a reference to a class function in a variable in PHP

Here is a hypothetical example (the parent class PageState, contains an instance of the class FooterState - the instance may not be created, depending on the conditions. The FooterState needs to call a function which is public and is created in the PageState class):
class PageState {
private $footer_state = null;
function PageState() {
$this->footer_state= new FooterState($this);
}
public function getExpectedPageDimensions() {
// do calculations based on existing body content
return $dimensions;
}
}
class FooterState {
private $get_dimensions_func = null;
function FooterState($page_state) {
// Here, we need to get the reference to the function from the $page_state class
$this->get_dimensions_func = $page_state->getExpectedPageDimensions;
}
public function addLogos($logo_data) {
$page_dimensions = $this->get_dimensions_func();
// use the page dimensions to decide on the size of the content
return Array('width' => $width, 'height' => $height);
}
I am aware of alternative solutions:
Instead of making a copy of the reference to the function, create a refference to the class $this->page_state = $page_state; and then functions in FooterState can call $this->page_state->getExpectedPageDimensions();
Use global $PageStateInstance; and then just call $PageStateInstance->getExpectedPageDimensions();
But I am wondering if it is at all possible to store a reference to a class function in a variable. If the functions were outside of the class, it would be possible to do stuff like $func = 'getExpectedPageDimensions'; $func();.
You can pass on an instance plus a function as a callable: An array with the instance and the function name. There is a similar system for calling static class methods.
# An example callback method
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
# create an instance
$obj = new MyClass();
# and later:
call_user_func(array($obj, 'myCallbackMethod'));
From the docs here: http://php.net/manual/en/language.types.callable.php
Instead of making a copy of the reference to the function, create a refference to the class $this->page_state = $page_state; and then functions in FooterState can call $this->page_state->getExpectedPageDimensions();
This is the best generic solution.
But I am wondering if it is at all possible to store a reference to a class function in a variable.
Yes it is, but it really only works for static functions unless you instantiate the class. Example:
class A {
public static function doSomethingStatic() {
// ...
}
public function doSomethingElse() {
// ...
}
}
$somevar = 'A::doSomethingStatic';
$result = call_user_func($somevar); // calls A::doSomethingStatic();
$myA = new A();
$myref = array($myA, 'doSomethingElse');
$result = call_user_func($myref); // calls $myref->doSomethingElse();
Note that in the second example you have to instantiate the class and pass an array as the first parameter to call_user_func().
References: http://php.net/manual/en/function.call-user-func.php and http://php.net/manual/en/language.types.callable.php
is at all possible to store a reference to a class function
I think you mean object instead of class, but yes you can, with closures.
I don't think you need to though. $this->page_state seems like it'll work just fine.
Don't use globals.

Php call function from included file

I have a class and I am including the players.php file inside it.
class My_Class {
private $player_types;
public function __construct() {
$this->player_types = 'classic';
require_once('players.php');
}
public function getPlayerTypes() {
return $this->player_types;
}
}
$mc = new My_Class();
How can I call getPlayerTypes function from players.php?
Also if its better to maybe use static method?
Just write :
$result = $this->getPlayerTypes();
echo $result;
inside the players.php. Definitely this will work.
Since the getPlayerTypes() is a method defined in the class My_Class, if you want to call that method from players.php you should instantiate a new My_Class object in that file and call the getPlayerTypes() there.
//player.php
$mc = new My_Class();
$playerTypes = $mc->getPlayerTypes();
echo $playerTypes
and remove that
require_once('players.php');
from your class :)
Since you are instantiating the class with the variable $mc, you'd call the function using
$mc->getPlayerTypes();
Or you can assign a variable to the result,
$result = $mc->getPlayerTypes();
echo $result;

How do I give reference to functions from one class to another?

The following is my simplified code
<?php
$database = new db();
$file = new file();
$input = new input();
$output = new output();
$data = "SELECT * FROM table;";
$input->page($data);
class db {
public function queryExecute($var) {
$var = $this->queryEncode($var);
$var = $this->querySubmit($var);
return $var;
}
public function queryEncode($var) {
// Do somthing
return $var;
}
public function querySubmit($var) {
// Do somthing
return $var;
}
}
The issue is when I add this to the code:
class input {
public function page($data) {
// Do something
$pageQuery = db::queryExecute($data);
}
}
With this, there are two things I have to do. First, I have to hide the errors for the db::queryExecute($data); code if the server is set to strict. And now for the second problem. I can't seem to use this line of code (which is the only way I have yet found possible for referencing other classes besides using Abstract) if the class that is being referenced is referencing yet another class but this time within it's own class.
For better explanation, the procedure is as follows:
Grab the $data variable and send it to the $input->page() function ( $input->page($data) ).
Referencing the db class, the $input->page() function sends the information onto the $database->queryExecute() function by means of the db::queryExecute() format ( db::queryExecute($data) ).
But because we are using the ::, when $database->queryExecute() references $database->queryEncode() and $database->querySubmit() using $this-> operator ( $this->queryEncode() and $this->querySubmit() ), $this-> currently belongs to $input-> and not $database->.
So what's the solution... Reference the other class differently (instead of ::)? Use a $_GLOBAL variable when I define my classes? Use something other than $this->? Configure all of the classes to use ABSTRACT/EXTENDS (or INTERFACE)?
The following error outputted refers to $var = $this->queryEncode($var);:
Fatal error: Call to undefined method input::querySubmit() in C:\[...]\global.php on line 12
Do not make static call to not static function. Pass $db instance to page, or provide global access to the database (via global registry, singleton or other method). But best, pass the dependency - the database instance, to the method.
<?php
$database = new db();
$file = new file();
$input = new input($database);
$output = new output();
$data = "SELECT * FROM table;";
$input->page($data);
class db {
public function queryExecute($var) {
$var = $this->queryEncode($var);
$var = $this->querySubmit($var);
return $var;
}
public function queryEncode($var) {
// Do somthing
return $var;
}
public function querySubmit($var) {
// Do somthing
return $var;
}
}
class input {
protected $_database;
public function __construct($database) {
$this->_database = $database;
}
public function page($data) {
// Do something
$pageQuery = $this->_database->queryExecute($data);
}
}
You can only use the double-colon operator on static, constant, or overridden properties or methods of a class. See the documentation on this. Use -> instead.

Categories