How can I create a local shortcut to an instance method? - php

In Python I can do this in a class instance method:
esc = self.super_long_escape_function_name
print esc(param1) + ", " + esc(param2)
In PHP, this is the closest "equivalent" I've been able to concoct:
$self = $this;
$esc = function($str) use($self) {
return $self->super_long_escape_function_name($str);
};
echo $esc($param1) . ", " . $esc($param2);
and I wouldn't really even call that an equivalent. I also tried this without success:
$esc = '$this->super_long_escape_function_name';
Are there any good ways of creating a local shortcut for a class instance method?

Right after asking this question, I discovered that this works:
$esc = array($this, "super_long_escape_function_name");
echo $esc($param1) . ", " . $esc($param2);
This doesn't work in PHP 5.3 though, so I will accept a better answer if it comes along.

Try this one
$esc = array($this, "super_long_escape_function_name");
echo $esc($param1) . ", " . $esc($param2);

Related

Handling empty lists in PHP SOAP

Initially if there was one item in the list it would return an object rather than an array of one object. I fixed that using:
https://eirikhoem.wordpress.com/2008/03/13/array-problems-with-soap-and-php-updated/
$x = new SoapClient($wsdl, array('features' => SOAP_SINGLE_ELEMENT_ARRAYS));
But I'm having problems when there is no items in the list.
The best I've come up with so far is:
$occulist = $result->GetWebOccurrencesResult->OccuList;
if (!empty((array)($occulist))) {
foreach($occulist->TOccu as $occurrence) {
echo $occurrence->Prog_Name . ' running from ' . $occurrence->StartDate . ' to ' . $occurrence->EndDate . '<br/>';
}
}
Originally it was
foreach($result->GetWebOccurrencesResult->OccuList->TOccu as $occurrence) {
I don't understand exactly what you're trying to achieve here, so if you can clarify in the comments, that'd be great.
What I'm taking from your question is that you want to handle when the array is empty, but want a clean method to do so? The loop you have there would do what you require, but here is another alternative:
do {
foreach($occulist->TOccu as $occurrence) {
echo $occurrence->Prog_Name . ' running from ' . $occurrence->StartDate . ' to ' . $occurrence->EndDate . '<br/>';
}
} while(empty((array)($occulist)) !== FALSE);
So you're looping through the foreach while the $occulist array isn't empty.
You could even do:
while((array)$occulist !== FALSE) {
foreach(....) {
...
}
}
On my server with Windows and PHP 5.4.23 this:
if (!empty((array)($occulist))) {
gives the following error:
Parse error: syntax error, unexpected '(array)' (array) (T_ARRAY_CAST)
I fixed it using:
if (get_object_vars($occulist)) {
I think that is a more elegant alternative to the original...

email generator in javascript and php

i have a javascript and php code that makes an email address hard for bots to find. i have it implemented on one site thats very basic and it works perfect, however on this other site with many more elements—something seems to go awry and it wont work.
the javascript adds in the mailto: and # functions
in the php, the elements are called in and the javascript runs to complete the function when you click on it——making it like a regular mailto: function.
is there something i'm missing in terms of perhaps DOM or global elements or something?
i have this script being called in my
header.php:
<script type="text/javascript" src="javascript/scripts.js"></script>
scripts.js:
function blind(name,domain) {
str = "mailto:" + name + "#" + domain;
window.location = str;
}
emailgen.php:
function showContacts()
{
global $debe;
$return ="";
$return .="
<div>";
$contactitems = $debe->runSql("SELECT * FROM contacts ORDER BY imp");
for($i=0; $i<count($contactitems); $i++)
{
$parts = explode('#', substr($contactitems[$i][3], $pos + 0));
$return .="
<p>" . $contactitems[$i][1] . "<br />
" . $parts[0] . "#" . $parts[1] . "<br />
</p>";
}
return $return;
}
when i view the source, it seems to show up okay but for some reason the mailto: isn't calling.
viewsource of emailgen.php:
name#email.com<br />
Add a single quote after $parts[0] . ":
" . $parts[0] . "#" . $parts[1] . "<br />

NetBeans code template for using all the arguments declared in the function's header

Is it possible to write a NetBeans code template for using all the arguments declared in a function's header (e.g. for calling another function with these variables)? The number of the arguments can be different, so it doesn't seem to be easy.
For example, sometimes I want to print out all the arguments in a function for debugging purposes.
Here's an example usage (calling dsm() function multiple times depending on the number of the arguments):
function testModule_theme($existing, $type, $theme, $path) {
dsm($existing, '$existing in ' . __FUNCTION__ . '()');
dsm($type, '$type in ' . __FUNCTION__ . '()');
dsm($theme, '$theme in ' . __FUNCTION__ . '()');
dsm($path, '$path in ' . __FUNCTION__ . '()');
return array(
// ......
);
}
Here's another one:
function testModule_block_view($delta = '') {
dsm($delta, '$delta in ' . __FUNCTION__ . '()');
$block = array();
// .....
return $block;
}
As you can see, there are 4 arguments in the first case, and only 1 in the second. The name of the arguments is also changing depending on the given function.
There's a code template I already wrote for using dsm() function:
dsm($$${VARIABLE newVarName default="variables"}, '$$${VARIABLE} in '.__FUNCTION__.'()');
this way I just type ddsm, hit Tab, and then I have to type the exact name of the variable. So it would print out the following:
dsm($variables, '$variables in ' . __FUNCTION__ . '()');
After that, I can change the variables part, and type another name, and the same would be used in the string. An example:
But I'm still too laggard to type that stuff :D, and I'm curious if there is a way to use all the arguments of a given function when using a code template in NetBeans.
This really seems difficult. If you knew you will be using the macro when you declare the function, you could use templates like this:
// shortcut dsmfun1
function ${FUNCTION_NAME}($$${PAR1}) {
dsm($$${PAR1}, '$$${PAR1} in ' . __FUNCTION__ . '()');
${selection}${cursor}
}
...
// shortcut dsmfun4
function ${FUNCTION_NAME}($$${PAR1}, $$${PAR2}, $$${PAR3}, $$${PAR4}) {
dsm($$${PAR1}, '$$${PAR1} in ' . __FUNCTION__ . '()');
dsm($$${PAR2}, '$$${PAR2} in ' . __FUNCTION__ . '()');
dsm($$${PAR3}, '$$${PAR3} in ' . __FUNCTION__ . '()');
dsm($$${PAR4}, '$$${PAR4} in ' . __FUNCTION__ . '()');
${selection}${cursor}
}
Couple templates give you really quick declaration and you have to type the parameters' names only once.
If you are adding these macros later, you might want to have a look at this doc and implement your desired behavior (even though that might be quite tricky).
Hope this helps!
Why don't you just use get_defined_vars() to pass them all in one shot? This way, your macro only needs to be a single static line.
function dsm($func, array $args)
{
foreach ($args as $name => $value) {
echo "in $func, arg '$name' is $value\n";
}
}
function testModule_theme($existing, $type, $theme, $path) {
dsm(__FUNCTION__, get_defined_vars());
}
testModule_theme(1, 2, 3, 4);
Output:
in testModule_theme, arg 'existing' is 1
in testModule_theme, arg 'type' is 2
in testModule_theme, arg 'theme' is 3
in testModule_theme, arg 'path' is 4

Is there an easier/shorter way to get geographic coordinates from GoogleMaps?

I'm currently using the following method to get coordinates from GoogleMaps.
Can I possibly write this shorter/more efficient?
EDIT 21.06.2013
As of now the old Google Geocoding API is off. This is my modified code that works with the most recent version. I've updated this post, if someone stumbles over it and finds it useful.
public function getGeographicCoordinatesFromGoogle()
{
// create address string
$value = $this->address_line_1 . ' ' .
$this->postal_code . ' ' .
$this->city . ' ' .
$this->country;
$value = preg_replace('!\s+!', '+', $value);
// create request
$request = 'http://maps.googleapis.com/maps/api/geocode/xml?address=' .
$value . '&sensor=false';
// get value from xml request
$xml = file_get_contents($request);
$doc = new \DOMDocument('1.0', 'UTF-8');
#$doc->loadXML($xml);
// fetch result
$result = $doc->getElementsByTagName('lat')->item(0)->nodeValue . ',' .
$doc->getElementsByTagName('lng')->item(0)->nodeValue;
// check result
if (!preg_match('/(-?\d+\.\d+),(-?\d+\.\d+)/', $result) ) {
$result = null;
}
// assign value
$this->setGeographicCoordinates($result);
}
You can use json instead of xml. json is newer, lightweight and object orientated.
I'll recommend you to use http_build_query() instead of trying to build the SearchQuery with Regex. There are other chars which need to be escaped.
This is a quite long method. Maybe it would make sense to have one Class which only handles the communication with GoogleMaps (Class GeoBackend with methods getGeoDataForAddress(), which returns a GeoData-Object, which could be asked for Cordinates etc.)

native php function to highlight javascript?

Is there any native PHP function as highlight_string(); but for javascript ?
Or, if not, is there any PHP function (homemade) to do it?
EDIT: I want to use PHP function to COLORIZE javascript
I have had great success with GeSHi. Easy to use and integrate in your app and it supports a lot of languages.
I understand you want a Syntax Highligher written in PHP. This one (Geshi) has worked for me in the past:
http://qbnz.com/highlighter/
Yes, the PHP function highlight_string() is a native PHP function for PHP.
No.
But there are a lot of javascript libraries that do syntax-highlight on several languages,
from bash-scripting to php and javascript.
eg, like snippet (JQuery) or jQuery.Syntax (my favorite)
Over here you can find an excellent library which enables syntax highlighting in a large amount of languages using javascripts and a css class.
There is no native php function to do this, so either you have to use existing libraries or you have to write something yourself.
Fastest way - you can use also PHP function "highlight_string" with a little trick
(capture function output and remove leading/trailing PHP tags):
$source = '... some javascript ...';
// option 1 - pure JS code
$htmlJs = highlight_string('<?php '.$source.' ?>', true);
$htmlJs = str_replace(array('<?php ', ' ?>'), array('', ''), $htmlJs);
// option 2 - when mixing up with PHP code inside of JS script
$htmlJs = highlight_string('START<?php '.$source.' ?>END', true);
$htmlJs = str_replace(array('START<span style="color: #0000BB"><?php </span>', ' ?>END'), array('', ''), $htmlJs);
// check PHP INI setting for "highlight.keyword" (#0000BB) - http://www.php.net/manual/en/misc.configuration.php#ini.syntax-highlighting
No native function, but rather than using a full stack library just to highlight some javascript you can use this single function :
function format_javascript($data, $options = false, $c_string = "#DD0000", $c_comment = "#FF8000", $c_keyword = "#007700", $c_default = "#0000BB", $c_html = "#0000BB", $flush_on_closing_brace = false)
{
if (is_array($options)) { // check for alternative usage
extract($options, EXTR_OVERWRITE); // extract the variables from the array if so
} else {
$advanced_optimizations = $options; // otherwise carry on as normal
}
#ini_set('highlight.string', $c_string); // Set each colour for each part of the syntax
#ini_set('highlight.comment', $c_comment); // Suppression has to happen as some hosts deny access to ini_set and there is no way of detecting this
#ini_set('highlight.keyword', $c_keyword);
#ini_set('highlight.default', $c_default);
#ini_set('highlight.html', $c_html);
if ($advanced_optimizations) { // if the function has been allowed to perform potential (although unlikely) code-destroying or erroneous edits
$data = preg_replace('/([$a-zA-z09]+) = \((.+)\) \? ([^]*)([ ]+)?\:([ ]+)?([^=\;]*)/', 'if ($2) {' . "\n" . ' $1 = $3; }' . "\n" . 'else {' . "\n" . ' $1 = $5; ' . "\n" . '}', $data); // expand all BASIC ternary statements into full if/elses
}
$data = str_replace(array(') { ', ' }', ";", "\r\n"), array(") {\n", "\n}", ";\n", "\n"), $data); // Newlinefy all braces and change Windows linebreaks to Linux (much nicer!)
$data = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $data); // Regex identifies all extra empty lines produced by the str_replace above. It is quicker to do it like this than deal with a more complicated regular expression above.
$data = str_replace("<?php", "<script>", highlight_string("<?php \n" . $data . "\n?>", true));
$data = explode("\n", str_replace(array("<br />"), array("\n"), $data));
# experimental tab level highlighting
$tab = 0;
$output = '';
foreach ($data as $line) {
$lineecho = $line;
if (substr_count($line, "\t") != $tab) {
$lineecho = str_replace("\t", "", trim($lineecho));
$lineecho = str_repeat("\t", $tab) . $lineecho;
}
$tab = $tab + substr_count($line, "{") - substr_count($line, "}");
if ($flush_on_closing_brace && trim($line) == "}") {
$output .= '}';
} else {
$output .= str_replace(array("{}", "[]"), array("<span style='color:" . $c_string . "!important;'>{}</span>", "<span style='color:" . $c_string . " !important;'>[]</span>"), $lineecho . "\n"); // Main JS specific thing that is not matched in the PHP parser
}
}
$output = str_replace(array('?php', '?>'), array('script type="text/javascript">', '</script>'), $output); // Add nice and friendly <script> tags around highlighted text
return '<pre id="code_highlighted">' . $output . "</pre>";
}
Usage :
echo format_javascript('console.log("Here is some highlighted JS code using a single function !");') ;
Credit :
http://css-tricks.com/highlight-code-with-php/
Demo :
http://css-tricks.com/examples/HighlightJavaScript/
Well nice info here . Here is another nice one : http://code.google.com/p/google-code-prettify/

Categories