Php call function from included file - php

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;

Related

How to make a class stored data to a variable an callback with method?

I am interested in how this works:
<?php
$Query = $mysqli->query("select * from table");
$Query->fetch_array(); // <== How to make $Query a class/method like this?
?>
How do you assign a method to a variable and then have that variable be able to call another method like the $mysqli and $Query example above?
One way to achieve what you are (I think) referring to, is by returning an object. It goes against the principle of dependency injection, but it's one way to do it.
class MyClassA
{
public function myFunction()
{
return new MyClassB();
}
}
class MyClassB
{
public function execute()
{
return true;
}
}
// Start use
$class = new MyClassA();
// Assign variable to function which returns object
$newObj = $class->myFunction();
// Will write "1" because now $newObj is MyClassB()
echo $newObj->execute();
Another way is to return $this from the first method. The usage of the above object would work identical in this instance, however you also allow another principle known as method chaining:
class MyClassA
{
public function myFunction()
{
return $this;
}
public function execute()
{
return true;
}
}
// Same as above works
$class = new MyClassA();
$sameObj = $class->myFunction();
echo $sameObj->execute();
// Allowing for Method Chain
$class = new MyClassA();
// Allowing for chaining
echo $class->myFunction()->execute();
You have to instantiate your class and call it's function with ->
$class = new MyClass(); // Instantiate class
$class->myFunction(); // Use it's function
PHP manual example of creating a class:
http://php.net/manual/en/language.oop5.basic.php

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(){

Passing a class as function parameter

I'm trying to do something like this:
function doSomething($param, Class) {
Class::someFunction();
}
$someVar = doSomething($param, Class);
Is it possible?
To explain better what I'm trying to do. I have a helper function in Laravel to generate unique slugs, so I have to query different tables depending on where the slug is going to be saved.
Actual code I'm trying to write:
$newcat->slug = $helper->uniqueSlug($appname, Apk);
public function uniqueSlug($str, Apk)
{
$slug = Str::slug($str);
$count = Apk::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
Thanks!
You can use the magic ::class constant:
public function uniqueSlug($str, $model)
{
$slug = Str::slug($str);
$count = $model::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
return $count ? "{$slug}-{$count}" : $slug;
}
$newcat->slug = $helper->uniqueSlug($appname, Apk::class);
In PHP, classes (or class names) are handled as strings. Since PHP 5.5, you can use YourClass::class to get a fully qualified class name.
If you want to get it in an earlier version of php, you can (if you have already an object of the calss) either do the following:
<?php
$obj = new YourClass();
// some code
$clazz = get_class($obj);
?>
or, you can implement a static method in your class, like this:
<?php
class YourClass {
// some code
public static function getClassName() {
return get_called_class();
}
?>
If you want to pass a class to a function, you can do it like this:
<?php
function do_somthing($arg1, $clazz) {
$clazz::someStaticMethod($arg1);
}
?>
or
<?php
function do_somthing($arg1, $clazz) {
call_user_func(array($clazz, 'someStaticMethod')), $arg1);
}
?>
If you need to call a non-static method of that class, you need to instanciate it:
<?php
function do_somthing($arg1, $clazz) {
$obj = new $clazz();
$obj->someNonStaticMethod();
}
?>
Note: You can use PHP type hinting with passed class names:
<?php
function do_somthing($arg1, MyInterface $clazz) {
$obj = new $clazz();
$obj->someInterfaceMethod();
}
?>
I think you can.
Send the class name as string parameter then use it like below.
$classtr = "yourparam";// param comes from the function call.
$obj = new $classtr;
$obj->method();
Send the class name as string parameter you need use the namespace. For example:
function defineClass()
{
$class = "App\MyClass"; // mention the namespace too
}
function reciveClass($class)
{
$class:: // what do you need,
}

PHP call Class method / function

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

PHP - passing variables to classes

I trying to learn OOP and I've made this class
class boo{
function boo(&another_class, $some_normal_variable){
$some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $another_class->get($some_normal_variable);
}
}
and I call this somewhere inside the another_class class like
$bla = new boo($bla, $foo);
echo $bla->do_stuff();
But I don't know how to access $bla, $foo inside the do_stuff function
<?php
class Boo
{
private $bar;
public function setBar( $value )
{
$this->bar = $value;
}
public function getValue()
{
return $this->bar;
}
}
$x = new Boo();
$x->setBar( 15 );
print 'Value of bar: ' . $x->getValue() . PHP_EOL;
Please don't pass by reference in PHP 5, there is no need for it and I've read it's actually slower.
I declared the variable in the class, though you don't have to do that.
Ok, first off, use the newer style constructor __construct instead of a method with the class name.
class boo{
public function __construct($another_class, $some_normal_variable){
Second, to answer your specific question, you need to use member variables/properties:
class boo {
protected $another_class = null;
protected $some_normal_variable = null;
public function __construct($another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $some_normal_variable;
}
function do_stuff(){
return $this->another_class->get($this->some_normal_variable);
}
}
Now, note that for member variables, inside of the class we reference them by prefixing them with $this->. That's because the property is bound to this instance of the class. That's what you're looking for...
In PHP, constructors and destructors are written with special names (__construct() and __destruct(), respectively). Access instance variables using $this->. Here's a rewrite of your class to use this:
class boo{
function __construct(&another_class, $some_normal_variable){
$this->another_class = $another_class;
$this->some_normal_variable = $another_class->do_something();
}
function do_stuff(){
// how can I access '$another_class' and '$some_normal_variable' here?
return $this->another_class->get($this->some_normal_variable);
}
}
You need to capture the values in the class using $this:
$this->foo = $some_normal_variable

Categories