I have 2 file
file1.php
<?php
Class A
{
public static function _test
{
}
}
function get_sql($id)
{
}
function get_data($ids)
{
}
?>
In file2.php I've written
require_once('file1.php');
$a = get_sql($id);
Why I cannot call the function and get my result??
try this in file1.php
<?php
Class A {
public static function _test {
}
function get_sql($id) {
echo $id;
}
function get_data($ids) {
}
}
?>
In file2.php first require the file and then code this
require_once('file1.php');
$a = new A();
$a->get_sql($id);
OR send static value in function
$a->get_sql(5);
This is your first mistake in your code
public static function _test{
}
} //this bracket is related to the class
Well for one thing you are not returning anything from the get_sql($id) function.
Assuming you are returning something in your original code; I hope you are aware that the function is not part of the class (its defined outside the scope of the class). But for educational purposes you would call a static method within a class by doing:
$a = A::get_sql($id);
This would also mean the defining the function in the following manner:
Class A{
public static function get_sql($id){
echo $id;
}
}
it is the question if you want to have functions get_sql() and get_data() as a methods inside the A class:
If yes the code from user2727841 will work after you add the round brackets to the function public static function _test:
public static function _test()
{
}
Your code will work too after you add the same brackets to the same function but your function get_sql() and get_data() are outside the class A.
EDIT
I thought that these function are outside the class A.
Please, add the round brackets to the public static function _test in the class A - it is syntax error - than I hope it will work.
Related
I'am trying to make a reference to a static function inside a class:
class Test {
function __construct() {
$this->fn1 = self::fn2;
}
public static function fn2() {
}
}
then i get this error:
Undefined class constant 'fn2'
why?
Not sure if this is what you want, but at least this might give you a hint:
<?php
class Test {
function __construct() {
$this->fn = function(){
return self::realFn();
};
}
public function callFn (){
$fn = $this->fn ;//yes, assigning to a var first is needed. You could also use call_user_func
$fn();
}
public static function realFn() {
echo 'blah';
}
}
$x = new Test();
$x->callFn();
You can test it here: https://3v4l.org/KVohi
You have defined a static function:
Test {
function__construct()
{
$this->fn1 = self::fn2();
}
public static function fn2()
{
}
}
Updated
If you want to assign a function to a variable, it is best to do this
with annonymous aka lambda functions since they are first class citizens and may be freely passed, returned and assigned. PHP is not unique in dealing with static method references in this fashion as JAVA implements them similarly:
Method references ... are compact, easy-to-read lambda expressions for
methods that already have a name.
You may create an anonymous function based on a callable in PHP, and so the OP may wish to do as follows, which PHP 7.1.10 or higher supports:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function getClosure (){
return Closure::fromCallable(["Test","fn2"]);
}
}
echo Test::getClosure()(),"\n";
See live code here
In this example an anonymous function is created and returned by the static getClosure method. When one invokes this method, then it returns the closure whose content is the same as static method fn2. Next, the returned closure gets invoked which causes the name of static method fn2 to display.
For more info re closures from callables, see the Manual and the RFC.
With PHP 7 on up, you may create a complex callable. In the code below the complex callable is an invocable array:
<?php
class foo
{
public static function test()
{
return [__CLASS__, 'fn2'];
}
public static function fn2()
{
echo __METHOD__;
}
}
echo foo::test()();
See live code.
Note: Starting with PHP 7.0.23 you could create a complex callable using a string containing the class and method names separated by the double colon aka paaamayim nekudotayim; see here.
A solution that has broader PHP support is as follows:
<?php
class Test {
public static function fn2() {
return __METHOD__;
}
public static function tryme(){
return call_user_func(["Test","fn2"]);
}
}
// return closure and execute it
echo Test::tryme();
See live code
I have a class Database in database.php with 145 functions(17,000 lines) and now i've read this is bad practice, so i want sort out the functions correctly into specific classes rather than a "God" Class.
What i want to know is how do i call a function from another class? Below is an example; How do i call function two from within function one?
database.php
require("connect.php");
class Database {
private $connect;
function one() {
//call function two
}
}
forms.php
require("connect.php");
class Forms {
private $connect;
function two() {
//returns forms
}
}
How do i do this?
In the example you gave you would do:
function one() {
$forms = new Forms;
$forms->two();
}
Another option would be
function one() {
Forms::two();
}
And in Forms you would change the method to:
static function two() {
}
Is there a way to do something like this:
class Test {
if(!empty($somevariable)) {
public function somefunction() {
}
}
}
I know this might not be best practice, but I need to do this for a very specific problem I have, so is there anyway to do it?
I just want that function to be included in the class if that variable (which is tied to a URL param) is not empty. As it is written now, I get Error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Thanks!
It depends on the your specific use case, and I don't have enough info to give a specific answer, but I can think of one possible fix.
Extend the class, using an if statement. Put everything except the one function in AbstractTest.
<?php
abstract class AbstractTest
{
// Rest of your code in here
}
if (!empty($somevariable)) {
class Test extends AbstractTest {
public function somefunction() {
}
}
} else {
class Test extends AbstractTest { }
}
Now, the class Test only has the method somefunction if $somevariable isn't empty. Otherwise it directly extends AbstractTest and doesn't add the new method.
Call the required function if the variable is not empty.
<?php
class Test {
public function myFunct() {
//Function description
}
}
$oTest = new Test();
if(!empty($_GET['urlParam'])) {
oTest->myFunc();
}
?>
class Test {
public function somefunction() {
}
}
is all you need actually.
Please note that a function inside a class is called 'method'.
AFAIK you cannot have a condition out of the method in class scope (if that flows)
Class Test {
if (empty($Var)){
public function Test_Method (){
}
}
}
Will not work. Why not have it constantly exisisting but only call the method when it's needed?
Example:
Class Test {
public function Some_Method(){
return 23094; // Return something for example purpose
}
}
Then from your PHP:
$Var = ""; // set an empty string
$Class = new Test();
if (empty($Var)){
echo $Class->Some_Method(); // Will output if $Var is empty
}
Perhaps you trying to validate a string within OOP scope, then take this example:
Class New_Test {
public $Variable; // Set a public variable
public function Set(){
$This->Variable = "This is not empty"; // When calling, $this->variable will not be empty
}
public function Fail_Safe(){
return "something"; // return a string
}
}
Then out of Scope:
$Class = new New_Test();
if (empty($Class->Variable)){
$Class->Fail_Safe();
} // Call failsafe if the variable in OOP scope is empty
I'm trying to use myVar inside my of a method's function. I have already tried adding global but still nothing. I know this is probably basic but I can't seem to find it.
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
Whenever I try using $this I get this error: 'Using $this when not in object context in...'
You should use $this->myVar
See the PHP Documentation - The Basics
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
The pseudo-variable $this is available when a method is called from
within an object context. $this is a reference to the calling object
(usually the object to which the method belongs
Update:
In your new code sample, myInnerFunction is a nested function and is not accessible until the myFunction method is called. Once the myFunction method is called, the myInnerFunction becomes part of the global scope.
Maybe this is what you are looking for:
class myClass{
public $myVar;
public function myFunction() {
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
Inner functions like myInnerFunction are always global in scope, even if they are defined inside of a member function in a class. See this question for another similar example
So, to PHP, the following are (almost) equivalent:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
}
}
And
class myClass{
public $myVar;
public function myFunction() {
}
}
function myInnerFunction() {
//how do I use this variable here
echo $this->myVar;
}
Hopefully the second example illustrates why $this is not even in scope for myInnerFunction. The solution is simply to pass the variable as a parameter to the function.
Pass it as an argument to the inner function.
You can use ReflectionProperty:
$prop = new ReflectionProperty("SimpleClass", 'var');
Full example:
class myClass{
public $myVar;
public function myFunction() {
function myInnerFunction() {
//how do I use this variable here
$prop = new ReflectionProperty("SimpleClass", 'myVar');
}
}
}
The solution above is good when you need each instance to have an own value. If you need all instances to have a same you can use static:
class myClass
{
public static $myVar = "this is my var's value";
public function myClass() {
echo self::$myVar;
}
}
new myClass();
see here
i have got a static function> which is called
regenerateThumbnailsCron()
And I would like to execute this function by GET params, for example>
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();
But if I tryied to call this function in constructor>
class AdminImages extends AdminTab
...
public function __construct()
{
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();
}
I cannot execute this function.
Is any way, how to call this function before __construct to correctly execute?
Thanks very much for any advice.
EDIT>
I tried also with public function>
<?php
include 'AdminImages.php';
$images = new AdminImages();
$images->regenerateThumbnailsCron();
?>
But i got error>
Fatal error: Class 'AdminTab' not found
You need to do a include 'AdminTab.php'; as well, since your class extends that
Not completely sure I understand your question, are you saying that you have static class "B" which extends class "A", "A" having your regenerateThumbnailsCron() method which you want to call before anything else?
If so then try this:
<?php
class A {
private function regenerate() {
.... do something ....
}
}
class B extends A {
function __construct() {
if ($_GET["pass"] == "password") {
parent::regenerate();
}
}
function regenerateThunbnailsCron() {
.... do somethinig ....
}
}
$images = new B();
$images->regenerateThumbnailsCron();
?>
This way, your parent's "regenerate()" function would get called during the constructor. You can switch this around to be a static class if you want, which if your goal is to compartmentalise any variables and functions away from the global scope would be a better way.