I'm triyng to convert a normal script in PHP to OO. I'me having some troubles doing that for some things. one of that is call a function (or method) in a variable to use globally.
The initial code is the following:
$myVariable = myFunction();
function myFunction(){
// some code in here
}
I've triyed to do something like following but it doesen't work
class MyClass{
$myVariable = $this->myFunction();
function myFunction(){
// some code in here
}
}
Can someone help me?
You need to call the function in a method (most likely the constructor). if you want to access to the property all over the class definition do this:
// Imagine you have a global method like this
MyFunction() {
}
class MyClass {
// define a property that store the result of calling MyFunction()
protected $somethingThatYouNeed;
// constructor calls when you instantiate your class
public function __construct() {
$this->somethingThatYouNeed = myFunction();
}
public function otherMethod() {
// you can access your variable here by calling $this->somethingThatYouNeed
}
}
Related
I have really started to look at PHP Classes, and I can not understand why this does not work. I thought if you define a variable in the constructor you can call it by that variable name. That is not the case though(?), let me give you all an example:
class test {
public function __construct($item) {
$this->item= $anItem;
}
public function callvar() {
//Does not work
return $anItem;
}
public function callvar() {
//Works
return $this->item;
}
}
So my question is, am I doing something wrong? Or must you call a __construct variable by $this->item?
$anItem is local variable in construct function, so it isn't a variable for another method. But $this->item is property of test class so that every method in test class can access this property as a global variable
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 saw some codes that when they call php functions from another class they no longer use $this->functionName(),
they just refer immedietly to the function name, like functionName()
In my index.php
$help = new Helper();
$help->Test();
I wanted to call Test Function by not doing the $help.
How can this be done? Why is this possible?
In PHP you can mix a procedural style of programming with object oriented style. That means that function can either exist as member of a class, or as stand-alone functions.
Member functions (or methods) are are called using $classinstance->methodname() for normal (instance) methods, or ClassName::methodName() for static methods.
Standalone functions are just called without referring to a class or object whatsoever. You can put them in separate files, if you like.
The declaration and usage is as follows:
In example.php:
class MyClass
{
$member = 'Hello world';
function MyMethod()
{
// The method can use the instance variable (member variable)
// using $this to refer to the instance of the class
echo $this->member;
}
static function MyStaticMethod()
{
echo 'Hello static world';
}
}
function MyFunction()
{
echo 'Hello';
}
In index.php:
// To include the class and its methods, as well as the function.
require_once 'example.php';
// Call an instance method
$instance = new MyClass();
$instance->MyMethod();
// Call a static method
MyClass::MyStaticMethod();
// Call a stand-alone function
MyFunction();
A standalone function is defined like this:
function myfunction() {
# whatever
}
Also see http://www.php.net/manual/en/functions.user-defined.php
With the -> operator you reference a function from within a class.
<?php
class A {
public function a() {
$this->b(); //references the function b() in $this class
}
public function b() {
echo 'Was called from function a() in class A';
}
}
function c() {
echo "I'm just a simple function outside a class";
}
//now you can do following calls
$class_a = new A();
$class_a->a();
c(); //references function c() within the same scope
The output would be:
Was called from function a() in class A
I'm just a simple function outside a class
But you could also do the following: outsource the function c() into an external file like function_c.php
Now, you can include/require the file from anywhere else and use it's content:
include 'function_c.php';
c(); //the function is now available, although it was defined in another file
you can a function from another class from a class, example:
require "myExternClass.php";
class myClass extends myExternClass
{
public function a() {
$this->b(); /* function b is in the class myExternClass */
}
}
generally you can't call a method of an object without the object itself.
but for some cases when method does not actually uses any objects' properties it may be acceptable for testing purposes to invoke it with call_user_func_array, passing some dummy value instead of object.
class A {
var $a;
function doNop() { echo "Nop";}
function doA() { echo "[".$a."]"; }
}
// instead of this
$a = new A;
$a->doNop();
// you _may_ use this
A::doNop();
// but this will fail, because there's no object to apply doA() to.
A::doA();
class A_dummy { $a };
// however, for testing purposes you can provide a dummy instead of real A instance
$b = new A_dummy;
call_user_func(array($b, 'A::doA'));
You can wrap the code in question inside a regular function:
function TestClass() {
$help = new Helper();
return $help->Test();
}
Then, in your index.php file you can call the function like this:
TestClass();
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.