php function inside array - php

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;
}

Related

Laravel: Cannot use helper inside php shorthand array [duplicate]

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.

Extending page table with field using itemsProcFunc in TYPO3 6.2

I'm trying to extend the 'page' properties form by extending the page db table and TCA array from within an extension. This works, except that my custom function won't be called. If I replace my own itemsProcFunc line with a TYPO3 core function itemsProcFunc line it works, but with my own function it never works (I just get an empty result/selectlist, even when I simply return a dummy array: "return array('title','1');"....
Here's my code in my extension's ext_tables.php:
<?php
$TCA['pages']['columns'] += array(
'targetelement' => array(
'exclude' => 0,
'label' => 'Target element (first select a target page!)',
'config' => array (
'type' => 'select',
'items' => Array (
Array('',0),
),
'size' => 1,
'minitems' => 1,
'maxitems' => 1,
//'itemsProcFunc' => 'TYPO3\CMS\Backend\View\BackendLayoutView->addBackendLayoutItems',
'itemsProcFunc' => 'Vendor\Myextension\Controller\Hooks\CustomTargetElementSelector->getContentElements',
),
)
);
t3lib_extMgm::addToAllTCAtypes('pages', 'targetelement,', '2', 'after:nav_title');
t3lib_extMgm::addToAllTCAtypes('pages', 'targetelement', '1,5,4,199,254', 'after:title');
P.s. I replace Vendor\Myextension for my own namespace of course.
I don't know where to put my function file exactly, I assume in extension\Classes\Controllers\Hooks\CustomTargetElementSelector.php.
My ultimate goal is to display a list of content elements of the selected shortcut page UID..
P.s.2 my CustomTargetElementSelect.php file looks like this (contents just return a single item, dummy list result:
<?php
namespace Vendor\Myextension\Controller;
class CustomTargetElementsSelector extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {
public function getContentElements(array &$params,$pObj){
return array('title','uid');
}
}
First of all, an itemsProcFunc should be a simple class; I never tested if an Extbase controller context is available in an itemsProcFunc.
Your hook should (this is just a recommendation) reside in
yourext/Classes/Hook/CustomTargetElementSelector.php
Namespace:
namespace Vendor\Yourext\Hook;
class CustomTargetElementSelector {
[method inside]
}
After flushing the system cache, if the hook still has no function, set a die() statement within the function to find out if the function is called at all. Currently it cannot work because the location of your class (Controllers/Hooks) and the namespace (Controller) don't fit.
For the sake of full 6.2/7 compatibility, replace
t3lib_extMgm::
by
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::

How do you arrange PHP objects into arrays for display

I'm a PHP developer who typically uses arrays in lieu of objects, and I'd like to know if there are any best practices for object manipulation based on key values.
Take the following multi-dimensional array of events, typical of something you'd pull directly out of the database.
$events = array(
0=>array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20131010'
),
1=>array(
'eventid'=>2,
'title'=>'Second Event',
'date'=>'20131022'
),
2=>array(
'eventid'=>3,
'title'=>'Third Event',
'date'=>'20131010'
),
),
For display purposes in my template, I want to make this a multi-dimensional array based on the date first. This is fairly easy transformation that I use a helper function for.
assoc($events,'date','eventid');
Resulting in:
$events = array(
20131010=>array(
1 => array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20131010'
),
3 => array(
'eventid'=>3,
'title'=>'Third Event',
'date'=>'20131010'
),
),
20131022=>array(
2 => array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20121010'
),
),
),
In this way, I can easily run through the array on the template side for each date, create a header and for that date, and then display events for that day underneath.
I could go ahead and try to make a similar assoc() function for Objects, but it strikes me this should be a fairly common thing and there may be a standard way of doing it. If you had an object instead of an array for $events, how would you go about formatting it the second way I've described, or would you?
One additional piece of information: I am using CodeIgniter, in case it has some helper functions that I'm not aware of that could be useful.
In your assoc function you could do an is_object check and cast to an array if it is an object.
function your_assoc_func($events){
if(is_object($events)){
$events = (array)$events
}
// If the object is more complex cast any containing objects you may run across
foreach($events as $event){
if(is_object($event)){
$event = (array)$event
}
}
}

Zendframework2 Dependency Injection Confusion

I'm a little confused on how DI works with ZF2. I've spent the last couple of days trying to get my head around it. While I have made some progress a lot of it still baffles me...
Using this (http://akrabat.com/getting-started-with-zend-framework-2/) tutorial I managed to get a grasp that the following:
'di' => array('instance' => array(
'alias' => array(
'album' => 'Album\Controller\AlbumController',
),
'Album\Controller\AlbumController' => array(
'parameters' => array(
'albums' => 'Album\Model\Albums',
),
),
works because in our Album Controller class we have a setAlbum function. So when the DI class will call that setAlbums function and pass it the 'Album\Model\Albums' class.
Fine get that no problem..
Now let's look at this (which comes in the skeleton application off the zend site)
'Zend\View\HelperLoader' => array(
'parameters' => array(
'map' => array(
'url' => 'Application\View\Helper\Url',
),
),
),
Now i would expect there within the Zend\View\HelperLoader (or an inherited class) would contain a setMap() function that the DI class would pass an array. But this appears not to be the case. As I cannot find a setMap anywhere.
My question is first what am I not understanding about the way DI works with the ZF2... But also what does the code above (about zend\view\helper) actually do. I mean what does injecting 'map' => array('url' => 'Application\View\Helper\Url') into the Zend\View\HelperLoader actually do?
Thanks for any help anyone can give. I appreciate it's a beta framework and what answers I may get now not apply in a months time. But this all seems pretty fundamental and i'm just no getting it!
The DI configuration of ZF2 works indeed with the names of the arguments in the signature. It does not matter if this is done with a constructor or a explicit setter. The setter must, however, start with "set" to be recognized by Zend\Di\Di.
So if you have a class like this:
<?php
namespace Foo;
class Bar
{
public function __construct ($baz) {}
public function setSomethingElse ($bat) {}
}
You can inject both a $baz and a $bat:
'di' => array(
'instance' => array(
'Foo\Bar' => array(
'parameters' => array(
'baz' => 'Something\Here',
'bat' => 'Something\There',
),
),
),
)
For Zend\Di it does not matter what the function name exactly is, as long as it starts with "set" and the name of the argument is correct. That is why Foo\Bar::setSomethingElse($bat) works just like Foo\Bar::setBat($bat).
Just make sure you name your arguments correctly. For example, it is easy to do something like this:
<?php
namespace Foo;
class Bar
{
public function setCacheForBar ($cache) {}
public function setCacheForBaz ($cache) {}
}
But that will not work nicely together with Zend\Di.

Fatal Error when loading Catalog-settings in backend

On a fresh 1.5.0.1 Magento install when choosing Catalog from the settings->settings menu I get the following error:
Fatal error: Undefined class constant 'RANGE_CALCULATION_AUTO' in
/my-install-dir/app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php on line 33
Checked Step.php and it does not look damaged and contains the following:
class Mage_Adminhtml_Model_System_Config_Source_Price_Step
{
public function toOptionArray()
{
return array(
array(
'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_AUTO,
'label' => Mage::helper('adminhtml')->__('Automatic')
),
array(
'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_MANUAL,
'label' => Mage::helper('adminhtml')->__('Manual')
),
);
}
}`
Anyone know this error or how to fix it?
PHP is complaining that it can't find the constant on RANGE_CALCULATION_AUTO defined on the class Mage_Catalog_Model_Layer_Filter_Price
Based on your comments above, it sounds like you already checked the file at
app/code/core/Mage/Catalog/Model/Layer/Filter/Price.php
to ensure is had the correct constant defined.
const RANGE_CALCULATION_AUTO = 'auto';
Based on that, my guess would be there's a different Price.php being loaded for this class. This can happen if
Someone's placed a different version in community or local
Someone's monkied with the include path beyond Magento's normal monkey business
Check for files at
app/community/core/Mage/Catalog/Model/Layer/Filter/Price.php
app/local/core/Mage/Catalog/Model/Layer/Filter/Price.php
If that doesn't work, add some temporary debugging code to
app/code/core/Mage/Adminhtml/Model/System/Config/Source/Price/Step.php
that uses reflection to figure out what file PHP is loading the class from
class Mage_Adminhtml_Model_System_Config_Source_Price_Step
{
public function toOptionArray()
{
//NEW LINES HERE
$r = new ReflectionClass('Mage_Catalog_Model_Layer_Filter_Price');
var_dump($r->getFileName());
//echo $r->getFileName(); // if too long for var_dump
exit("Bailing at line ".__LINE__." in ".__FILE__);
//END NEW LINES
return array(
array(
'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_AUTO,
'label' => Mage::helper('adminhtml')->__('Automatic')
),
array(
'value' => Mage_Catalog_Model_Layer_Filter_Price::RANGE_CALCULATION_MANUAL,
'label' => Mage::helper('adminhtml')->__('Manual')
),
);
}
}`
This will dump out a file path that points to the exact place PHP is loading the class from, which should get you where you need to go.

Categories