This question already has answers here:
Is it possible to define a class property value dynamically in PHP?
(2 answers)
Closed 7 years ago.
PHP version 5.6. Code:
protected $siteServices = [
1 => [
'title' => 'Consulting',
'key' => 'service',
'description' => '',
'file' => asset('assets/img/sample/image1.jpg'), // throws error on this line
],
];
Error: PHP Parse error: syntax error, unexpected '(', expecting ']'
What would be a possible fix for this?
Edit
Solved by moving the variable in the running function instead of making it protected. Also can be solved by declaring the empty variable first then set the values in __constructor()
It could be done but it in a different way. I have listed two different methods.
First method
protected $siteServices = [
1 => [
'title' => 'Consulting',
'key' => 'service',
'description' => '',
'file' => ['asset', 'assets/img/sample/image1.jpg'] // throws error on this line
]
];
I replaced the function call with an array assigned to the file key in this array. So, now, you'd be wondering how you could call the asset function, yeah? It is pretty simple.
While you are looping through that array, you can do this:
call_user_func($siteServices[1]['file'][0], $siteServices[1]['file'][1]);
So, what are we doing here?
Firstly, we set an array to the file key where the first element of the array is the name of the function, while the other element is the value for the parameter that needs to be passed to the function defined previously.
So, using the PHP's call_user_func function, you can call functions giving their name and the parameters. I hope this helps you out.
Second method
I am pretty sure you will have a setter function for this property. Therefore, you could do something like this:
public function setSiteService($title, $key, $description, $file)
{
$file = asset($file);
$service = [
'title' => $title,
'key' => $key,
'description' => $description,
'file' => $file
];
$this->siteServices[] = $service;
}
So, the setter does the processing part for you. Hardcoding arrays is not at all a good idea, you should definitely populate through some mechanism.
Related
I have a private function to return an array of options, those options indicate a callback and other options such as template, form, etc. Here the code:
/**
* #return array
*/
private function options()
{
$options = [
'general' => [
'form' => GeneralConfigType::class,
'template' => 'general.html.twig',
'title' => 'ConfiguraciĆ³n General',
'ignoreFields' => ['slider', 'social'],
'uploadedFields' => [],
'callbacks' => ['generalData']
],
'business' => [
'form' => ConfigurationType::class,
'template' => 'business.html.twig',
'title' => 'ConfiguraciĆ³n de Empresa',
'ignoreFields' => [],
'uploadedFields' => ['image','favicon','login_icon','sidebar_icon'],
'callbacks' => ['businessImage']
],
];
return $options;
}
Now here is my doubt, in addition to indicate the function you have to execute in the key callback, Can I pass on the variables I'm going to need in that callback? I've tried several ways and they haven't worked.
Example:
Before:
'callbacks' => ['generalData']
After:
In this example I'm assigning the '$', but I could do it if the only string, I'm just looking for a way to pass to the callback the variables it needs and no more.
'callbacks' => ['generalData' => '$configurationData, $configuration, $form, $request']
And this code would be where everything would be executed in other method:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
$this->$callback($variables);
}
}
If I understand you correctly, you want to store the name of the variable in the array of options and then use that variable in the callback function.
When I've done this type of thing, I find it easier to just store the variable name as text and leave out the $ from the name stored in the array. I then use a variable variable when retrieving it.
Either way, I think you need a little more code on the execution side. One more loop:
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
foreach($variables as $variable){ // extra loop to get the variables
$this->$callback[$$variable];
// This is where it gets tricky, and depends on how you wish to format.
// The variables are currently part of an array, thus the array notation
// above. By using the stored name only, and a variable variable, you
// should be able to get to the var you need
}
}
}
#jcarlosweb, what you need to do is very simple. The short answer is that it can be done using the [call_user_func_array()][1] method.
In the context of your example, the callbacks could be rearranges in the following way ...
'callbacks' => ['generalData' => [$configurationData, $configuration, $form, $request]
Basically, the array keys will be the name of the function to call, and the corresponding array values will be a array of the values of each parameter that is accepted but the callback function. Doing it this way is important because you need to capture the value of the parameters while they are in scope. And this will avoid using eval().
Using the callbacks can be as simple as ...
$options = options();
foreach ($options['callbacks'] as $callback => $params) {
$result = call_user_func_array($callback, $params);
// Do something with $result if necessary
}
I finally got it with the function compact http://php.net/manual/en/function.compact.php
Here's the code:
First I select the variables I need in my options:
'callbacks' => ['businessImage' => ['configurationData', 'configuration', 'form', 'request']]
Second I call the variables with compact, but I had to use extract here because if I didn't configurationData variable wasn't modified, which I don't understand since I had previously referenced it.
if (!empty($options[ 'callbacks' ])) {
foreach ($options[ 'callbacks' ] as $callback => $variables) {
$variables = compact($variables);
$this->$callback($variables);
extract($variables);
}
}
Third callback applied and referenced:
/**
* #param array $params
* #return array $configurationData
*/
private function businessImage(&$params)
{
extract($params,EXTR_REFS);
// more code here ......
$configurationData[ "image" ] = $originalImageName;
$configurationData[ "favicon" ] = $originalFaviconName;
$configurationData[ "login_icon" ] = $originalLoginIconName;
$configurationData[ "sidebar_icon" ] = $originalSidebarIconName;
return $configurationData;
}
This works correctly in my website, but as I said before I do not understand why I have to call back the function extract, if I have already passed it referenced in the same callback as you see in my last code.
I'm trying to pass data about the page state (navbar links having active class when you are in that exact page), page title. I do so with an indexed array $pageInfo, however I am getting a syntax error and doen't know where?
Also do you think this is a good method or should I use view->share() instead?
public function clases()
{
$pageInfo[] =
(
'page_title' => 'Clases',
'menu_active' => 'CLases',
'sub_menu_active' => '',
);
return view('clases.list', compact('pageInfo'));
}
public function domicilio()
{
$pageInfo[] =
(
'page_title' => 'Clases a domicilio',
'menu_active' => 'Clases',
'sub_menu_active' => 'Clases a domicilio',
);
return view('clases.domicilio', compact('pageInfo'));
I suggest you read PHP basic syntax.
Basically you want to do this:
$pageInfo =
[
'page_title' => 'Clases',
'menu_active' => 'CLases',
'sub_menu_active' => '',
];
Arrays have a syntax of [key => val, ...] in PHP, you're using () as it seems.
Also $someArray[] = someValue, will append the someValue to an existing array, in your case that would create another, unwanted level of your array.
And last, you're not ending the domicilio() function. But I'll assume you just didn't paste it in (you should add } at the end, if that's not the case).
I try to store a function inside an array but it keeps giving me this error:
unexpected 'function' (T_FUNCTION)
I looked around on internet but they mostly say that I should be using php version 5.3 and above, while I am using 5.6.21.
Here is my array:
static $Events = array(
'View Page' => array(
'properties' => array(
'previous_event',
'number_view_page',
),
'trigger' => function($foo){
return $foo;
},
),
);
If anyone knows what the problem is and how to solve it, please help me :)
static values need to be initialised with static/constant expressions. Sadly, anonymous functions aren't "constant" enough to count. Later PHP versions allow some limited expressions like 2 + 4 (because the result is always constant), but nothing more than that. Function declarations are too complex to handle in a static context (you can add a function to the array afterwards at any time, you just can't initialise it that way*).
* The reason for this restriction is that static declarations are handled at a different parsing phase than runtime code, and that parsing phase cannot handle anything but primitive values.
Try again with this (you have 2 ,, too much at the end of the code and please remove the static)
EDIT: adding function so you can use the array from other class.
function $events_func()
{
$events = array(
'View Page' => array(
'properties' => array(
'previous_event',
'number_view_page',
),
'trigger' => function($foo){
return $foo;
}
)
);
return $events;
}
I've seen a few example here on stack but they don't seem to cover this scenario.
I'm attempting this;
$flight_range = array(
array('range' => range(1,50), 'service' => 'Long Haul'),
array('range' => range(51,54), 'service' => 'Short Haul'),
....
);
but PHP won't let me. It returns;
Parse error: syntax error, unexpected '(', expecting ')' on line 02
This does not work either;
array(range(1,50), range(51,54) ...
The problem is with trying to assign a value of range().
I have 20+ sets of range values to assign.
Can anyone suggest an easy method for achieving these sorts of array values?
EDIT;
haike00, Jack and Sean are right.
Maybe my question should be how do i make $flight_range a member variable of a class;
private $flight_range = array(array('range' => range(1,50), 'service' => 'Long Haul'));
What is the problem with doing this in your constructor?
class MyClass {
private $flight_range;
public function __construct() {
$this->flight_range = array(
array(
'range' => range( 1, 50 ),
'service' => 'Long Haul'
)
);
}
}
Its working fine on my end.
$flight_range = array(
array('range' => range(1,50) , 'service' => 'Long Haul'), array('range' => range(51,54),'service' => 'Short Haul'));
print_r($flight_range);
Just copy and paste above code and run it.
Using the latest CakePHP build 1.3.6.
I'm writing a custom datasource for a external REST API. I've got all the read functionality working beautifully. I'm struggling with the Model::save & Model::create.
According to the documentation, the below methods must be implemented (see below and notice it does not mention calculate). These are all implemented. However, I was getting an "Fatal error: Call to undefined method ApiSource::calculate()". So I implemented the ApiSource::calculate() method.
describe($model) listSources() At
least one of:
create($model, $fields = array(), $values = array())
read($model, $queryData = array())
update($model, $fields = array(), $values = array())
delete($model, $id
= null)
public function calculate(&$model, $func, $params = array())
{
pr($model->data); // POST data
pr($func); // count
pr($params); // empty
return '__'.$func; // returning __count;
}
If make a call from my model
$this->save($this->data)
It is calling calculate, but none of the other implemented methods. I would expect it to either call ApiSource::create() or ApiSource::update()
Any thoughts or suggustions?
Leo, you tipped me in the right direction. The answer was in the model that was using the custom datasource. That model MUST define your _schema.
class User extends AppModel
{
public $name = 'User';
public $useDbConfig = 'cvs';
public $useTable = false;
public $_schema = array(
'firstName' => array(
'type' => 'string',
'length' => 30
),
'lastName' => array(
'type' => 'string',
'length' => 30
),
'email' => array(
'type' => 'string',
'length' => 50
),
'password' => array(
'type' => 'string',
'length' => 20
)
);
...
}
I'm guessing that if you implement a describe() method in the custom datasource that will solve the problem too. In this case it needed to be predefined to authorize the saves and/or creation.
From the API: http://api13.cakephp.org/class/dbo-source#method-DboSourcecalculate
"Returns an SQL calculation, i.e. COUNT() or MAX()"
A quick search in ~/cake finds 20 matches in 8 files. One of those is the definition in dbo_source.php
The other seven are:
dbo_source.test.php
code_coverage_manager.test.php
code_coverage_manager.php
dbo_db2.php
model.php
tree.php
containable.php
Without delving too deeply into this, I suspect your problem lies in Model::save
You'll probably have to define a calculate method to suit the structure of your custom datasource because Cake won't know how to do that.