PHP anonymous function causes syntax error on some installations - syntax-error

I have the following code:
$file_check_method_func = function($n) {
$n = absint($n);
if(1 !== $n) { $n = 0; }
return $n;
};
$valid['file_check_method'] = array_map($file_check_method_func, $input['file_check_method']);
This works on my PHP 5.3.5 installation but when I run this code on a PHP 5.2.15 installation I get:
Parse error: syntax error, unexpected T_FUNCTION in /home/xxxx/public_html/xxxx/xxxxxxx/wp-content/plugins/wordpress-file-monitor-plus/classes/wpfmp.settings.class.php on line 220
Line 220 being the first line of the above code.
So my question(s), is there something wrongly written in my code that would give this error? If not is it because of a bug or not supported feature in PHP 5.2.15? If yes then how can I write the above code so not to generate the error?
The above code is in a function in a class.

Anonymous functions is a feature added in 5.3
For earlier versions, create a named function and refer it by name. Eg.:
function file_check_method_func($n) {
$n = absint($n);
if(1 !== $n) { $n = 0; }
return $n;
}
$valid['file_check_method'] = array_map('file_check_method_func', $input['file_check_method']);
or inside a class:
class Foo {
protected function file_check_method_func($n) {
$n = absint($n);
if(1 !== $n) { $n = 0; }
return $n;
}
function validate($input) {
$valid = array();
$valid['file_check_method'] = array_map(array($this, 'file_check_method_func'), $input['file_check_method']);
return $valid;
}
}
I would strongly suggest not to rely on create_function.

The syntax for anonymous functions in the example can only be used in PHP >= 5.3. Before PHP 5.3, anonymous functions can only be created with create_function().

Anonymous functions using this function-syntax has been added 5.3. But you can define anonymous functions using http://www.php.net/manual/en/function.create-function.php

Related

How to return error as value from failable function?

The current release of Zig is 0.10.1 at the time of asking this question. The language is not yet stable and is subject to change.
How can I return an error as value from a failable function? I have tried the following, but it returns it as an error instead of returning it as a value:
fn foo_1() !anyerror {
// Returns outer error.
return error.Oops;
}
fn foo_2() !anyerror {
// Returns outer error.
var error_ = error.Oops;
return error_;
}
I would like to return it as value such that the following code to print out the error instead of propagating it when try is evaluated:
fn bar() !void {
var error_ = try foo();
std.debug.print("got error: {any}\n", .{ error_ });
}
I am asking this because I am trying to learn the language. I don't have a concrete use-case for this. However, I am curious if this is possible to do.
A similar related situation is to return an optional value which itself is optional (for example when forwarding the result of a function which returns an optional), but I was already able to find a solution for that:
fn baz_1() ??i32 {
// The outer optional is null.
return null;
}
fn baz_2() ??i32 {
// The inner optional is null.
var value: ?i32 = null;
return value;
}
Is something like that possible for errors as well?
No, it's not allowed in Zig. If you try you'll get an error like "error union with payload of error set type 'error{Def}' not allowed".
However, you can wrap the error in a struct:
const std = #import("std");
const ErrorError = error{
Abc,
};
const ErrorValue = error{
Def,
};
const WrappedError = struct {
err: ErrorValue,
};
fn foo() ErrorError!WrappedError {
return .{
.err = ErrorValue.Def,
};
}
test "returns error value" {
var bar = try foo();
std.debug.assert(bar.err == ErrorValue.Def);
}
error values can be declared with error{...} syntax. see https://ziglang.org/documentation/master/#Errors
pub const Error = error{Bar};
fn foo() error{Bar} {
return error.Bar;
}
// or anyerror
fn foo() anyerror {
return error.Bar;
}

Returning a 'raw' scalar container from AT-POS method (rather than a Proxy instance) in a class that 'does' Positional?

I'm attempting to implement a class that 'does' Positional that also allows me to update its values by assigning to the result returned by the AT-POS method. Eventually, I was able to concoct the following class that works as intended:
class Test does Positional
{
has $.slot_1 is rw = 12;
has $.slot_2 is rw = 24;
method AT-POS(\position)
{
my $t = self;
return-rw Proxy.new:
FETCH => method ()
{
position % 2 ?? $t.slot_1 !! $t.slot_2
},
STORE => method ($v)
{
if position % 2
{
$t.slot_1 = $v
}
else
{
$t.slot_2 = $v
}
}
}
}
my $test = Test.new;
die unless $test[2] == 24;
die unless $test[5] == 12;
$test[7] = 120;
die unless $test[2] == 24;
die unless $test[5] == 120;
$test[10] = 240;
die unless $test[2] == 240;
die unless $test[5] == 120;
Would it be possible to somehow (and: simply) return the container bound to $!slot_1 (or $!slot_2) inside the Test class implementation?
Before I discovered the use of Proxy instances I attempted to return (and return-rw) the result of expression position % 2 ?? $!slot_1.VAR !! $!slot_2.VAR, because I'm under the impression that the VAR method gives me access to the underlying container, in the hope that I can simply return it. That didn't really work, and I do not understand why yet: I suspect it somehow gets coerced back to a value somehow?
So in other words: is it possible to simplify my AT-POS implementation in this particular situation?
Thanks,
Regards,
Raymond.
Assuming you do not want accessors for "slot_1" and "slot_2", and if I understand the question correctly, this would be my implementation. I wouldn't call it a Test class, as that would interfere with the Test class that is used for testing.
class Foo {
has #elements = 24, 12;
method AT-POS(Int:D $pos) is raw {
#elements[$pos % 2]
}
}
my $f = Foo.new;
say $f[2]; # 24
say $f[5]; # 12
$f[2] = 666;
say $f[4]; # 666
Note that the defaults in the array have changed order, that's to keep the arithmetic in AT-POS simple.
Also note the is raw in the definition of the AT-POS method: it will ensure that no de-containerization will take place when returning a value. This allows you to just assign to whatever $f[2] returns.
Hope this made sense!
Also: the Array::Agnostic module may be of interest for you, to use directly, or to use as a source of inspiration.
First off if you aren't going to use an attribute outside of the object, there isn't a reason to declare them as public, and especially not rw.
class Foo {
has $!odd = 12;
has $!even = 24;
…
}
You can also directly return a Scalar container from a method. You should declare the method as rw or raw. (raw doesn't guarantee that it is writable.)
class Foo {
has $!odd = 12;
has $!even = 24;
method AT-POS(\position) is rw {
position % 2 ?? $!odd !! $!even
}
}
# we actually get the Scalar container given to us
say Foo.new[10].VAR.name; # $!even
Note that even if you declare the attributes as public they still have a private name. The private attribute is always rw even if it isn't publicly declared as rw.
class Foo {
has $.odd = 12;
has $.even = 24;
method AT-POS(\position) is rw {
position % 2 ?? $!odd !! $!even
}
}
If you are going to use a Proxy, I would consider moving the common code outside of it.
class Foo {
has $.odd = 12;
has $.even = 24;
method AT-POS(\position) is rw {
# no need to write this twice
my $alias := (position % 2 ?? $!odd !! $!even);
Proxy.new:
FETCH => method () { $alias },
STORE => method ($new-value) { $alias = $new-value }
}
}
Of course the ?? !! code is a core feature of this module, so it would make sense to put it into a single method so that you don't end up with duplicate code all over your class. In this case I made it a private method.
class Foo {
has $.odd = 12;
has $.even = 24;
# has to be either `raw` or `rw`
# it is debatable of which is better here
method !attr(\position) is raw {
position % 2 ?? $!odd !! $!even
}
method AT-POS(\position) is rw {
my $alias := self!attr(position);
Proxy.new:
FETCH => -> $ { $alias },
STORE => -> $, $new-value { $alias = $new-value }
}
}
Again, not much reason to use a Proxy.
class Foo {
has $.odd = 12;
has $.even = 24;
method !attr(\position) is raw {
position % 2 ?? $!odd !! $!even
}
method AT-POS(\position) is rw {
self!attr(position);
}
}
Instead of ?? !! you could use an indexing operation.
method !attr(\position) is raw {
($!even,$!odd)[position % 2]
}
Which would allow for a ternary data structure.
method !attr(\position) is raw {
($!mod0,$!mod1,$!mod2)[position % 3]
}
There was no need to write the if statement that you did as Raku usually passes Scalar containers around instead of the value.
(position % 2 ?? $t.slot_1 !! $t.slot_2) = $v;

Laravel: Find exact match, case sensitive

This code works but it is not sensitive to case/capitalization.
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(function($query) use ($search){
$query->where('barcode','=',"$search")
})->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}
Example
Searching for 'banana123' should NOT be equal to 'BaNaNa123' and should return 0.
How can we make the search exact match? Thank you.
You have to use BINARY
use DB;
...
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(function($query) use ($search){
$query->whereRaw("BINARY `barcode` = '$search'");
// or
// $query->where(DB::raw("BINARY `barcode`), $search);
})->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}
Also if you are using one where and not chaining it to other conditions you don't need to use function inside where. you can simply write:
use DB;
...
public function search(){
if ($search = \Request::get('q')) {
$patrons = Patron::where(DB::raw("BINARY `barcode`"), $search)->paginate(20);
}else{
$patrons = Patron::latest()->paginate(5);
}
return $patrons;
}

Broken return type declarations in PHP7?

I can't do something like this:
$a = 5;
function a():int use($a) {
return $a + 5;
}
Do return type declaration break scope inheritance?
You can only use the use keyword for inheriting variables in anonymous functions (closures). This has nothing to do with the declared return type.
See http://php.net/manual/en/functions.anonymous.php
To clarify a bit here is an example:
$a = 1;
$func = function () use ( $a ) {
return $a + 1;
}
// Call the closure that has captured $a
$func();

Dojo scope question for store.query with ItemFileWriteStore

I am writing a method to grab the lowest unique id in an ItemFileWriteStore. I have a boolean to tell me when I reach my condition, but I can't get the scope correct.
The function call works as I expect, apart from when newIdOkay is set to true, it is not recognised in the while loop.
Please can you explain why and what I have to do to get this right?
Many thanks
Here is my code:
function checkNewId( size ) {
if( size == 0 ) {
console.log('found new ID!');
newIdOkay = true;
}
}
function addContentItem( store ) {
// New ID
var newIdOkay = false;
var newId = 0;
while( newIdOkay == false && newId < 8 ) {
newId++;
store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),
start:0, count:0, sync:true });
}
}
To understand the reason, you need to have basic understanding of identifier resolution and scope chain in JavaScript. I recommend you to read this article: http://jibbering.com/faq/notes/closures/
Regarding you question, in the function addContentItem, the check in the while loop is tested against the identifier newIdOkay which is in the of the activation object corresponding to this function execution context. In the function checkNewId, the identifier newIdOkay you set is in the global object. So these two are not the same one. An easy fix is to move the newIdOkay in addContentItem function to the global scope.
var newIdOkay = false;
function checkNewId( size ) {
if( size == 0 ) {
console.log('found new ID!');
newIdOkay = true;
}
}
function addContentItem( store ) {
// New ID
var newId = 0;
while( newIdOkay == false && newId < 8 ) {
newId++;
store.fetch({ query: {id:newId}, onBegin: dojo.hitch(this, "checkNewId"),
start:0, count:0, sync:true });
}
}