PHP comes with huge set of functions that can be called from Phel by just adding a php/
prefix to the function name.
(php/strlen "test") # Calls PHP's strlen function and evaluates to 4
(php/date "l") # Evaluates to something like "Monday"
(php/new expr args*)
Evaluates expr
and creates a new PHP class using the arguments. The instance of the class is returned.
(ns my\module
(:use \DateTime))
(php/new DateTime) # Returns a new instance of the DateTime class
(php/new DateTime "now") # Returns a new instance of the DateTime class
(php/new "\\DateTimeImmutable") # instantiate a new PHP class from string
(php/-> (methodname expr*))
(php/-> property)
Calls a method or property on a PHP object. Both methodname
and property
must be symbols and cannot be an evaluated value.
(ns my\module
(:use \DateInterval))
(def di (php/new \DateInterval "PT30S"))
(php/-> di (format "%s seconds")) # Evaluates to "30 seconds"
(php/-> di s) # Evaluates to 30
(php/:: (methodname expr*))
(php/:: property)
Same as above, but for static calls on PHP classes.
(ns my\module
(:use \DateTimeImmutable))
(php/:: DateTimeImmutable ATOM) # Evaluates to "Y-m-d\TH:i:sP"
# Evaluates to a new instance of DateTimeImmutable
(php/:: DateTimeImmutable (createFromFormat "Y-m-d" "2020-03-22"))
(php/aget arr index)
Equivalent to PHP's arr[index] ?? null
.
(php/aget ["a" "b" "c"] 0) # Evaluates to "a"
(php/aget (php/array "a" "b" "c") 1) # Evaluates to "b"
(php/aget (php/array "a" "b" "c") 5) # Evaluates to nil
(php/aset arr index value)
Equivalent to PHP's arr[index] = value
.
(php/apush arr value)
Equivalent to PHP's arr[] = value
.
(php/aunset arr index)
Equivalent to PHP's unset(arr[index])
.
__DIR__
and __FILE__
In Phel you can also use PHP Magic Methods __DIR__
and __FILE__
. These resolve to the dirname or filename of the Phel file.
(println __DIR__) # Prints the directory name of the file
(println __FILE__) # Prints the filename of the file