PHP class function not working - php

I'm new to PHP and web scripting in general so this a newb question.
Currently i'm a creating an instance to an object, yet when I call the constructor
the script slienty shuts down... it doesn't call the next function and I don't know why.
Any help would be welcome.
Here is the code.
<?php
class product {
var $ssProductName;
var $ssVendorName;
var $ssDescr;
var $ssURI;
// Clean constructor, strings must be cleaned before use
function __construct($ssProd, $ssVendor, $ssD, $ssU) {
$this->$ssProductName = $ssProd;
$this->$ssVendorName = $ssVendor;
$this->$ssDescr = $ssD;
$this->$ssURI = $ssU;
}
// print a table of the values
function DisplayOneEntry() {
echo '<table border="1">
<tr>
<td>'.$this->$ssProductName.'</td>
<td>'.$this->$ssVendorName.'</td>
<td>'.$this->$ssDescr.'</td>
<td>'.$this->$ssURI.'</td>
</tr>
</table>';
}
}
echo "<HTML>";
echo "A";
$newP = new product("Redhat", "Redhat corp", "Leader in", "www.redhat.com");
echo "B";
$newP->DisplayOneEntry();
echo "</HTML>";
?>
But the output is just:
<HTML>
A
Then nothing else.
This is running on a hosting provider using php 5.2.9 and Apache 2.2.

You need to access the member variables with:
$this->variableName
Not:
$this->$variableName

$this->$ssProductName = $ssProd;
should be
$this->ssProductName = $ssProd;
no $ after the ->

The syntax $this->$foo is a variable variable referencing the class attribute with the name of the value of $foo. So if $foo has the value bar, $this->$foo would reference $foo->bar and not $this->foo.
So just remove the $ after $this-> and it should work.

That is because your php script is erroneous. To catch such errors, you should run it on a debugging server (with display_errors set to On) or use other logging methods.
However, the main problem is you are accessing object members the wrong way; there's no second dollar sign. Instead of
$this->$ssProductName = $ssProd;
use
$this->ssProductName = $ssProd;

Related

Get the name a function was called as, equivalent to CFML's getFunctionCalledName()

Here is an example of the CFML code I am using as a baseline (also on github # getFunctionCalledName.cfm):
function f(){
echo("#getFunctionCalledName()#() called<br>");
}
f();
echo("<hr>");
g = f;
g();
This outputs:
F() called
G() called
Note that getFunctionCalledName() returns the name of the reference used to call the function, not simply the name of the function.
I'm trying to see if there's an equivalent in PHP. Here's my test of that (testFunction.php on GitHub):
I know there's the __FUNCTION__ magic constant:
function f()
{
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
f();
echo "<hr>";
$g = "f"; // as someone points out below, this is perhaps not analogous to the g = f in the CFML code above. I dunno how to simply make a new reference to a function (other than via using function expressions instead, which is not the same situation
$g();
However this returns f in both cases.
I've written similar code trying debug_backtrace() (see testDebugBackTrace.php), but that also references the function as f.
This is fine, and I understand why they both do that. However I'm wondering if there's any PHP equivalent of getFunctionCalledName(). I hasten to add this is just for an exploratory exercise: I am currently migrating myself from CFML to PHP and this just came up when I was demonstrating something on my blog.
Your code $g = "f"; isn't really copying the function to another variable, it's just creating a string reference to the same function. The following would be more analogous to the CFML you provide:
$x = function() {
echo __FUNCTION__;
};
$v = $x;
$v();
The above code just outputs {closure}, since PHP doesn't assign a formal name to anonymous functions. So, the answer is, no, it isn't possible in PHP.
I don't think what you're after is possible in PHP without something like the runkit extension. That has the functionality to create a copy of a function under a new name. I haven't tried this out myself as I couldn't find a Windows version of the extension.
http://php.net/manual/en/function.runkit-function-copy.php
<?php
function f() {
echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
runkit_function_copy('f', 'g');
f();
g();
?>

In PHP, can you DEFINE a constant that can be used in function names?

In Drupal, there are many functions that are hook_functionname1, hook_functionname2. When writing a module, you have to replace the text 'hook' with your module name, so Drupal loads your module "my_drupal_module" and runs hooks like "my_drupal_module_functionname1" and "my_drupal_module_functionname2".
Is it possible in PHP to use DEFINE to simply define the word "hook" and set it to a string? If it is possible, then you should be able to copy and paste word-for-word hook_anything and not have to change it. And, if you ever wanted to change the name of your module, you would merely change the single constant, rather than find/replace all the function names.
So can you use DEFINE or some other setting to meta-program in PHP?
You want something like:
$moduleFunctionName = 'hook';
$functionNameOne = $moduleFunctionName . '_functionname1';
$functionNameTwo = $moduleFunctionName . '_functionname2';
$functionNameOne = function($var) {
// blah
}
..//
Function $functionNameOne is defined through anonymous function. It becames available in php from php 5.3.0
Maybe you want something like this
<?
define('PREFIX', 'myprefix');
//like this time you deside that this will me the second part
$somevar = '_this_function_name';
// now we combine prefix and name
$function_name = PREFIX . $somevar;
// now we check if we can run this function
if(!function_exists($function_name)){
echo "no function $funcion_name exist";
}
else{
$function_name();
}
function myprefix_this_function_name(){
echo 'running function';
}
?>
this will output
running function
This actually works:
define('FN_NAMESPACE', 'hook_');
${FN_NAMESPACE . 'functionNameOne'} = function($var) {
echo "Hi, I got $var\n";
};
$hook_functionNameOne('test');
Will output
Hi, I got test

PHP By Reference variable

I'm a .net programmer that recently decided to check PHP out and so far I must say that it's quite fun.
I use WAMPServer to work with PHP and I'm having a problem when using by reference variables.
This is the code I'm using:
function drawCategories($parent_id, $catlistids="",$level=0,$selected="") {
global $USERLANG;
$result = mysql_query("
SELECT
BPPENNYAUTOBID_categories.cat_id,
BPPENNYAUTOBID_cats_translated.cat_name
FROM
BPPENNYAUTOBID_categories
INNER JOIN BPPENNYAUTOBID_cats_translated ON BPPENNYAUTOBID_categories.cat_id=BPPENNYAUTOBID_cats_translated.cat_id
WHERE
BPPENNYAUTOBID_cats_translated.cat_name!=''
AND BPPENNYAUTOBID_categories.parent_id='".$parent_id."'
AND BPPENNYAUTOBID_cats_translated.lang='".$USERLANG."'
ORDER BY
BPPENNYAUTOBID_categories.cat_name"
);
while ($line = mysql_fetch_array($result)) {
if($catlistids != "") { $catlistids .= "<br />"; }
$spaces = "";
for($i=0;$i<$level;$i++) $spaces .=" ";
$catlistids .= "<option value='".$line['cat_id']."' ".($selected==$line['cat_id'] ? " selected ":"").">".$spaces.$line["cat_name"]."</option>";
drawCategories($line["cat_id"], &$catlistids,$level+1,$selected);
}
return $catlistids;
}
When I call the drawCategories function the second time passing the variable $catlistids by reference then all the website content disapears, I don't get any kind of error but I suppose it's something to do with WAMP server definitions.
Can anyone help me solve this problem?
Thanks in advance
There is no reference sign on a function call - only on function definitions. Function definitions alone are enough to correctly pass the argument by reference. As of PHP 5.3.0, you will get a warning saying that "call-time pass-by-reference" is deprecated when you use & in foo(&$a);. And as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.
You can pass a variable by reference to a function so the function can modify the variable. Remove & from function call and try this way:
function drawCategories($parent_id, &$catlistids="", $level=0, $selected="") {
//^

global inside and outside a function in PHP?

I usually run code like this just fine:
$ZANE_REGISTER_RULES='this wont print';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='this will actually print';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
But sometime (eg: if I put this inside a phpBB page) this doesn't work (the echo says "this wont print") unless I declare the variable global the first time too:
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='funziona';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
I'm pretty sure that the first way is the correct one and the second one just doesn't mean anything, nevertheless the second one works, the first one doesn't.
PLEASE don't waste time replying "global are bad programming" because this is not the issue at hand, neither "why would you do such a thing?" because this is obviusly an example.
There is only one reason why this might be happening: the code in the second example is being compiled in the context of a function. That's why $ZANE_REGISTER_RULES has local scope by default.
If there is no enclosing function in the source file where the code itself appears, this means that the file is being included by some other file inside a function context, for example:
var_access.php
echo "Hello ".$name."\n";
echo "Hello ".$_GLOBALS['name']."\n";
test_1.php
// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice
test_2.php
// Here var_access.php is included in a function context
$name = 'world';
function func() {
$name = 'function world';
include('var_access.php'); // Prints "Hello world" and "Hello function world"
}

Always get an empty array in foreach loop

There are two columns in the database table "system". I have the systemId and want to get the mobileSystemId. But the variable $mobileSystemIds which I already defined as global is always empty.
EDIT: Now array_map doesn´t work. I always get my Exception output "Arrayfehler ArrayMap"
I have the following code :
$mobileSystemIds=array();
function getMobileSystemId($systemId)
{
global $mysqli;
global $mobileSystemIds;
$query="SELECT mobileSystemId FROM system WHERE systemId ='" .$systemId ."'";
if(!$result=$mysqli->query($query))
{
echo "Datenbankfehler DB-QUery";
exit(0);
}
if (!$mobileSystemId=$result->fetch_assoc())
{
echo "Datenbankfehler DB-Fetch";
exit(0);
}
$mobileSystemId=$mobileSystemId["mobileSystemId"];
echo "mobile System ID: " .$mobileSystemId ."<br />";
return $mobileSystemId;
}
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
In this case, using a return in your function would be much cleaner.
Nothing to do with your problem, but is your $systemId var trusted ? (To prevent SQL injection).
Update:
if(!$mobileSystemIds=array_map("getMobileSystemId",$systemList))
{
echo "Arrayfehler ArrayMap";
}
ought to read (just checked; it works for me):
$mobileSystemIds = array_map('getMobileSystemId', $systemsList);
if (empty($mobileSystemIds))
{
if (empty($systemsList) || !(is_array($systemsList)))
echo "OK: no mobile IDs, but no systems either";
else
echo "THIS now is strange :-(";
}
else
{
echo "Alles OK";
var_dump($mobileSystemIds);
}
I tried this by returning a dummy value based on input; if it does not work for you, there must be something strange in the database.
(Update: the text below refers to your original code, which did not use array mapping)
Your code ought to be working as it is. You put several $mobileSystemId 's into a single $mobileSystemId.
It works: I tested with a simpler code, removing the DB calls but leaving your code, and spelling, untouched.
So, the error must be elsewhere. I would guess that this code is included into something else, and:
the $mobileSystemIds = array(); declaration gets executed more than once, thereby losing all its data;
the $mobileSystemIds = array(); declaration is itself included in a more local scope and you read it from outside, reading an empty value or a totally different value.
Try replacing the first part of your code with:
GLOBAL $mobileSystemsIds;
if (defined($mobileSystemsIds))
trigger_error("mobileSystemsId defined more than once", E_USER_ERROR);
else
$mobileSystemsIds = array();
and also, in the function body:
if (!defined($mobileSystemsId))
trigger_error("mobileSystemsId should have been defined", E_USER_ERROR);

Categories