I am trying to make a small PHP function which can check if a constant is defined, and if so, echo it, and if not, echo space or nothing.
Right now, the if(defined() part is not working, because the constant is being transferred to a variable inside the function.
function getConstant($constant) {
if(defined($constant)) {
echo constant($constant);
} else {
echo '';
}
}
The echo constant($constant) part is working fine, but I cannot check if the constant is actually defined because it is a variable now.
I cannot seem to find a solution for it
public static function isConstants($constant) {
$oClass = new ReflectionClass(__CLASS__);
$allConstants = $oClass->getConstants();
if (isset($allConstants[$constant])) {
echo $allConstants[$constant];
} else {
echo '';
}
}
Related
<?php if(isset($staff['FirstName'])){echo encodeToUtf8($staff['FirstName'];} ?>
code above is the code source of my costume function, I create a function to make my code more shorter than the previous one.
this is my function:
function ifset($table_name, $field_name){
if(isset($table_name[$field_name])){
encodeToUtf8($table_name[$field_name]);
}
return $table_name;
return $field_name;
}
so that I can use the code must shorter like this <?php echo ifset($staff, 'IDNumber'); ?>
but it's not working, it give error : Undefined variable if field has no value and not what a expected.
have someone any idea about this case.
You can't return two statements in a single function. You could return as an array.
function ifset($table_name, $field_name){
if(isset($table_name[$field_name])){
encodeToUtf8($table_name[$field_name]);
}
return array($table_name,$field_name);
}
You can then access it using a list.
list($table, $field) = ifset($staff, 'IDNumber');
The return statement is wrong. Here is the fix:
function ifset($table_name, $field_name)
{
if(isset($table_name[$field_name]))
{
return encodeToUtf8($table_name[$field_name]);
}
return '';
}
Hello Id like to know how to call the function I just written from URL?
Bellow are my php code.
<?php
require 'db.php';
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
?>
I tried http://127.0.0.1/study/sf.php?function=l1 but it wont echo the written code.
Please point me to the right direction.
Yes you could supply that parameter into calling your user defined function:
$func = $_GET['function'];
$func();
Might as well filter the ones you have defined thru get_defined_functions
function l1(){
echo "Hello there!";
}
function l2(){
echo "I have no Idea what Im doing!";
}
function l3(){
echo "I'm just a year 1 college student dont torture me sir!";
}
$functions = $arr = get_defined_functions()['user']; // defined functions
if(!empty($_GET['function']) && in_array($_GET['function'], $functions)) {
$func = $_GET['function'];
$func();
}
Sample Output
Sidenote: function_exists can be also applied as well:
if(!empty($_GET['function']) && function_exists($_GET['function'])) {
// invoke function
}
One option you can do if use if/elseifs like so:
if($_GET['function'] == 'l1')
{
l1();
}
else if($_GET['function'] == 'l2')
{
l2();
}
Or you could use a riskier approach and call the function name directly from the input.
$functionName = $_GET['function'];
$functionName();
Edit:
Or you could use a switch statement:
switch($_GET['function'])
{
case 'l1':
l1();
break;
case 'l2':
l2();
break;
case 'l3':
l3();
break;
}
Inherited an old CakePHP site and I'm trying to figure out what some functions do. I have several functions that have the same name as another function but with an underscore first, e.g. save() and _save(). However the function _save() is never called in any context, though save() is.
I read this question and it looks like it's from an old worst-practices exercise, but that doesn't really explain why it's in my code; you still have to call function _save() as _save() right? If there's no calls to _save() is it safe to remove?
I want it gone, even the save() function wasn't supposed to be there, rewriting perfectly good framework functionality. It looks like an older version of the same function, but there's no comments and I don't know if there's some weird context in which php/Cake will fall back to the underscored function name.
Here's the code for the curious. On closer inspection it appears the underscored functions were old versions of a function left in for some reason. At least one was a "private" method being called (from a public function of the same name, minus the underscore...):
function __save() {
$user = $this->redirectWithoutPermission('product.manage','/',true);
if ($this->data) {
$this->Prod->data = $this->data;
$saved_okay = false;
if ($this->Prod->validates()) {
if ($this->Prod->save()) $saved_okay = true;
}
if ($saved_okay) {
$product_id = ($this->data['Prod']['id']) ? $this->data['Prod']['id'] : $this->Prod->getLastInsertId();
if ($this->data['Plant']['id']) {
$this->data['Prod']['id'] = $product_id;
$this->Prod->data = $this->data;
$this->Prod->save_plants();
$this->redirect('/plant/products/'.$this->data['Plant']['id']);
} else {
$this->redirect('/product/view/'.$product_id);
}
die();
} else {
die('did not save properly');
}
} else {
die('whoops');
}
}
function save() {
$user = $this->redirectWithoutPermission('product.manage','/products',true);
if ($this->data) {
$this->Prod->data = $this->data;
if ($this->Prod->validates()) {
$this->Prod->save();
$gotoURL = isset($this->data['Navigation']['goto'])?$this->data['Navigation']['goto']:'/';
$gotoURL = str_replace('%%Prod.id%%', $this->data['Prod']['id'], $gotoURL);
if (isset($this->data['Navigation']['flash'])) {
$this->Session->setFlash($this->data['Navigation']['flash']);
}
if (isset($this->params['url']['ext']) && $this->params['url']['ext']=='ajax') {
$value = array(
'success'=>true
,'redirect'=>$gotoURL
);
print $this->Json->encode($value);
} else {
$this->redirect($gotoURL);
}
} else {
$value = array(
'success'=>false
,'message'=>"You have invalid fields."
,'reason'=>'invalid_fields'
,'fields'=>array(
'Prod'=>$this->Prod->invalidFields()
)
);
print $this->Json->encode($value);
}
} else {
$this->redirect('/products');
}
die();
}
I had hoped to learn whether or not some convention applied to this situation, but from testing I've found the functions are not called which is really the answer to the question I asked.
so im making homepage with three languages.
I am using switch method, here is code -
public function languages()
{
if (isset($_GET['lang']) && $_GET['lang'] != '')
{
$_SESSION['lang'] = $_GET['lang'];
}
else
{
$_SESSION['lang'] = 'en_EN';
}
switch($_SESSION['lang'])
{
case 'en_EN': require_once('language/lang.eng.php');break;
case 'lv_LV': require_once('language/lang.lv.php');break;
case 'ru_RU': require_once('language/lang.ru.php');break;
default: require_once('language/lang.eng.php');
}
}
public function translate($txt)
{
global $text;
return $text[$txt];
}
and it should display in index.php file like this -
<?php $index->translate('search'); ?>
but the problem is that it shows no errors, no notices, no warnings and no translated or default text.
I included function languages() , maybe you can help me with this problem?
EDIT:
im calling $language at start of index.php file - <?php require_once('class.index.php'); $index = new index; $index->languages(); ?> and $text is defined in lang.eng.php; lang.lv.php and lang.ru.php file.
Since you're using a class, I think it's better to use properties instead of globals, it will be easier in future mantainance. Create a class variable holding $text and use that
class Index {
var $text;
public function languages()
{
require(".....");
$this->text = $text;
}
public function translate($txt)
{
if(isset($this->text[$txt]))
{
return $this->text[$txt];
}
else
{
return "no translation";
}
}
}
$index = new Index;
$index->languages();
echo $index->translate('search');
type
<?php echo $index->translate('search'); ?>
Check first whether the session is initialized or not and also place the languages() function call before the translate so that it loads the language prior to translation and also put error_reporting(E_ALL) at top so that any error suppresion will be be removed and also put echo the returned result of translate statement
i have created below function in a file info.php to debug variable & data during page load
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".__METHOD__;
echo "<br/>LINE:".__LINE__;
}
}
}
now i call this method from another page index.php, where i inculded info.php
in this file i want to debug POST array, so i write below code
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch($postarray,'POST ARRAY', TRUE);
}
everything is working fine but method and LINE appears below
METHOD:Info::watch();
LINE:17 // ( where this code is written in Info class)
but i wantbelow to display
METHOD: Testpost::gtPostdata()
LINE:5( where this function is called in Testpost class)
so how do i do that if i put$more=TRUE in watch() then method and line number should be diaply from the class where it is called.
can i use self:: or parent::in watch method?? or something else
please suggest me how to call magic constants from other classes or is there any other method to debug varaibale?? ( please dont suggest to use Xdebug or any other tools)
You have to use the debug_backtrace() php function.
You also have below the solution to your problem. Enjoy! :)
<?php
class Info {
static function watch($what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
$backtrace = debug_backtrace();
if (isset($backtrace[1]))
{
echo "<br/>METHOD:".$backtrace[1]['function'];
echo "<br/>LINE:".$backtrace[1]['line'];
}
}
}
}
You can not use those constants from that scope. Check out the function debug_backtrace() instead. If it gives you too much info, try to parse it.
debug_bactrace is the only way you could totally automate this, but it's a "heavy-duty" function.... very slow to execute, and needs parsing to extract the required information. It might seem cumbersome, but a far better solution is to pass the necessary information to your Info::watch method:
class Info {
static function watch($whereClass,$whereLine,$what,$msg='',$more=FALSE)
{
echo "<hr/>";
echo "<br/>".$msg.":";
if( is_array($what) || is_object($what) )
{
echo "<pre>";
print_r($what);
echo "</pre>";
}
else{
echo $what;
}
if($more)
{
echo "<br/>METHOD:".$whereClass;
echo "<br/>LINE:".$whereLine;
}
}
}
now i call this method from another page index.php, where i inculded info.php
class Testpost {
__construct() { // some basic intializtion }
function getPostdata($postarray) {
$postarray=$_POST;
Info::watch(__METHOD__,__LINE__,$postarray,'POST ARRAY', TRUE);
}