This question already exists:
Access array element from function call in php [duplicate]
Closed 8 years ago.
I'm fairly new to PHP and I am trying to return an array from a class function and then access its values like so:
<?php
class Foo
{
private $access;
public function setAccess($access)
{
$this->access = $access;
}
public function getAccess()
{
return $this->access;
}
}
$var = new Foo();
$var->setAccess(array(1,2,3,4));
$var2 = $var->getAccess()[2];
echo $var2;
?>
When I try to run a page with this code, I get the following:
Parse error: syntax error, unexpected '[' in arraytest.php on line 22
How can I access the values for my private arrays in my class?
This:
$var2 = $var->getAccess()[2];
can't be done in PHP before version 5.4 (this feature is called array dereferencing). At the moment you have to do something like this:
$var2 = $var->getAccess();
$var2 = $var2[2];
you can't call an array value directly like that, you'd have to write this:
$access = $var->getAccess();
$var2 = $access[2];
alternatively, you could add a function like this to your class.
public function getAccessValue($key) {
return $this->access[$key];
}
Related
This question already has answers here:
Sharing var from one function to the other function in PHP Class
(2 answers)
Closed 4 years ago.
Let's say I have two different functions, and one of them has a defined variable. In the second function, I don't wanna write the same variable again, can I simply use the variable from the first function in the second one WITHOUT redefining it in the second function?
Someting like:
class example{
public function a($foo){
$foo2 = $foo + 1
return $foo2;
}
public function b($foo2){
echo "result: " . $foo2;
}
}
It's simple, you can use a property $foo2 and access it from both methods:
class example{
private $foo2;
public function a($foo){
$this->foo2 = $foo + 1
return $this->foo2;
}
public function b(){
echo "result: " . $this->foo2;
}
}
$obj = new example();
$obj->a(5);
$obj->b(); // result: 6
This question already has answers here:
php call class function by string name
(6 answers)
Closed 8 years ago.
In PHP5, variables can be evaluated as functions1 such as:
function myFunc() {
echo "whatever";
}
$callableFunction = 'myFunc';
$callableFunction(); // executes myFunc()
Is there any syntax for assigning object member functions to a variable such as:
class MyClass {
function someCall() {
echo "yay";
}
}
$class = new MyClass();
// what I would like:
$assignedFunction = $class->someCall; // but I tried and it returns an error
$memberFunc = 'someCall';
$class->$memberFunc(); // I know this is valid, but I want a single variable to be able to be used to call different functions - I don't want to have to know whether it is part of a class or not.
// my current implementation because I don't know how to do it with anonymous functions:
$assignedFunction = function() { return $class->someCall(); } // <- seems lengthy; would be more efficient if I can just assign $class->someCall to the variable somehow?
$assignedFunction(); // I would like this to execute $class->someCall()
There is a way, but for php 5.4 and above...
class MyClass {
function someCall() {
echo "yay";
}
}
$obj = new Myclass();
$ref = array($obj, 'someCall');
$ref();
Hm.. actually it works for static too, just use the reference by name..
class MyClass {
static function someCall2() {
echo "yay2";
}
}
$ref = array('MyClass', 'someCall2');
$ref();
And for nonstatic this notation works as well. It creates a temporary instance of the class. So, this is what you need, only you need php 5.4 and above )
The PHP 5.4 solution above is good. If you need PHP 5.3, I don't think you can do much better than the anonymous function approach, but you could wrap that into a function that acts very similar to the PHP 5.4 method:
function buildCallable($obj, $function)
{
return function () use ($obj, $function) {
$args = func_get_args();
return call_user_func_array(array($obj, $function), $args);
};
}
//example
class MyClass
{
public function add($x, $y)
{
return $x + $y;
}
public static function multiply($x, $y)
{
return $x * $y;
}
}
//non-static methods
$callable = buildCallable(new MyClass(), 'add');
echo $callable(32, 10);
//static methods
$callable = buildCallable('MyClass', 'multiply');
echo $callable(21, 2);
This should work for any number of arguments to any (publicly visible) method.
This question already has answers here:
DEFINE vs Variable in PHP
(5 answers)
Closed 9 years ago.
by define I mean using define function.
What I want to know is can I shorten this:
$GLOBALS['MY_VAR'] to MY_VAR ... and use it in any scope! (not having to use global $myvar; in functions).
EDIT:
example: print_r(MY_VAR['somekey']); gives error!
EDIT:
I understand it makes a constant variable, but isn't it a constant pointer to the array? I thought arrays are mutable in php?
Define refers to a constant and not a global. Constants can be used anywhere. Below is how you would use it with the example you gave.
define( 'MY_VAR', $GLOBALS['MY_VAR'] );
More info here: http://uk1.php.net/define
Hm, is it always a constant? I guess a better way is you build your own token. If you do so, you can access from anywhere your token and edit, read or change the values within this token.
For your needs, build a token class (just copy and paste it to file named MyTokenHolder.php):
class MyTokenHolder
{
protected static $_sessionkey = "BE SURE TO OVERRIDE THIS KEY";
//Define your values here
public $Username;
public $UserID;
public function __construct()
{
if(isset($_SESSION[self::$_sessionkey]))
{
$token = unserialize(base64_decode($_SESSION[self::$_sessionkey]));
//see above public params
$this->Username = $token->Username;
$this->UserID = (int)$token->UserID;
}
}
public function SaveToSession()
{
$_SESSION[self::$_sessionkey] = base64_encode(serialize($this));
}
public static function DestroySession()
{
unset($_SESSION[self::$_sessionkey]);
}
}
Now, you can set the values, which are defined within the token:
//Set Values
$token = new MyTokenHolder();
$token->Username = 'test';
$token->UserID = 99;
$token->SaveToSession();
And also you can read your values from token.
//Read Values
$token = new MyTokenHolder();
echo $token->UserID;
echo $token->Username;
Test your self here - SQL Fiddle: http://ideone.com/jj7r6l
Try this :
define("CONSTANT","anything");
and you can use CONSTANT anywhere in any scope.
example :
define("CONSTANT","123abc321");
function test(){
return CONSTANT;
}
echo test(); //echoes 123abc321
But
Note that you can't assign an array to a constant value.
This question already has an answer here:
Can't initialize a PDO object in a class as a property [duplicate]
(1 answer)
Closed 9 years ago.
sorry for the noobish question.
I'm new with PHP class programming and I can't figure out why this piece of code doesn't work:
class Job {
private $var1 = 'hi there';
private $var2 = date('Y/m/d');
public function foo() { /* some code */ }
}
$job = new Job();
I get parse error parse error, expecting','' or ';'' generated by $var2.
Looks like I can't initialize a variable inside a class from a PHP function.
How can I bypass this error?
Thank in advance.
Initialize it from within the constructor:
class Job {
private $var1 = 'hi there';
private $var2 = null;
public function __construct() { $this->var2 = date("Y/m/d"); }
public function foo() { /* some code */ }
}
$job = new Job();
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling closure assigned to object property directly
If I have a class like this:
class test{
function one(){
$this->two()->func(); //Since $test is returned, why can I not call func()?
}
function two(){
$test = (object) array();
$test->func = function(){
echo 'Does this work?';
};
return $test;
}
}
$new = new test;
$new->one(); //Expecting 'Does this work?'
So my question is, when I call function two from function one, function two returns the $test variable which has a closure function of func() attached to it. Why can I not call that as a chained method?
Edit
I just remembered that this can also be done by using $this->func->__invoke() for anyone that needs that.
Because this is currently a limitation of PHP. What you are doing is logical and should be possible. In fact, you can work around the limitation by writing:
function one(){
call_user_func($this->two()->func);
}
or
function one(){
$f = $this->two()->func;
$f();
}
Stupid, I know.