PHP - Problem With Calling A Method From Within A Method In Another Class
My script has 3 classes (that are relevant to this discussion): DB, User and Validate. They are all in independent files and loaded automatically, when required, by an autoloader.
The error messages I am getting a Any pointers as to what I am doing wrong, or what I should be doing, would be most welcome. Similar TutorialsOk. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. i have a constructor Quote public function __construct(){ // check if any action related to this page was generated if(isset($_GET['action'])){ $this->action = ucwords($_GET['action']) . '()'; self::{$this->maction}; } //code to generate the list of all the systems users $user = new userDAO; $this->results = $user->fetchAll(); } if action is present in the querystring, eg. delete, it would be stored into $this->action as Delete(). Similarly, if the action was edit, it would be stored as Edit(). My intent is to call the method named Delete() or Edit() depending upon which action was generated. I have defined the methods in the same class. Once i assign the current action to the $this->action, i want to call the method without explicitly specifying the method name.... here i have tried self::$this->action.... i even tried $this->action only but its not working? i think the string stored in the self::$this->action is not being interpolated? or....sth. i dont know. pls help out guys So i have an url routing class set up. I wan to call method via url so it would look something like this: http://www.mysite.com/index.php/Class/Method/Parameter. I was able to instantiate class like this: Code: [Select] $controller = new $this->UrlPath[0]; But i can't call method the same way Code: [Select] $controller->$this->UrlPath[1](); Is there a way to call method with an array? Hi, I've a two classes A,B. A is a parent class and B is a child class. B is extends from A. I made an object of class A. Now i want to access function of class B from this object instance. e.g Code: [Select] class A { function myfunctiona() { ....... ....... } } class B extends A { function chlidfunction() { return "hyne"; } } $sani = new A(); //here i want to access echo $sani->b->childfunction(); please guide how can called child class function from parent object instance? Thanks I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me <?php $headers[0] = 'Content-Type: text/namevalue'; $headers[1] = 'X-PAYPAL-SECURITY-USERID: blah'; $headers[2] = 'X-PAYPAL-SECURITY-PASSWORD: blah'; $headers[3] = 'X-PAYPAL-SECURITY-SIGNATU blah'; $headers[4] = 'X-PAYPAL-APPLICATION-ID: blah'; $headers[5] = 'X-PAYPAL-REQUEST-DATA-FORMAT: NV'; $headers[6] = 'X-PAYPAL-RESPONSE-DATA-FORMAT: NV'; $endpoint = 'https://api-3t.paypal.com/nvp'; $method = 'BMGetButtonDetails(hostedbuttonid:AUKAUSD1)'; $options = array('http' => array('header' => 'Content-type: application/x-www-form-urlencoded', 'method' => 'POST', 'content' => http_build_query($method))); $response = file_get_contents($endpoint, $method, $options, $headers); header('Location: gwpvlist.mv?done=aukretrieved&pvi=AUK&actioni=list&identityi=AUKMUSD1&sesx=54467585000E3C510000766200000000&ans='.$response);?>
It seems to go somewhere but there is nothing in $response.
By the way, I am an infant at php usage. (and an imbecile otherwise!)
If a class has a constructor but also has a static method, if I call the static method does the constructor run so that I can use an output from the constructor in my static method? --Kenoli I found class on the net, and i am having a bit of a problem to understand how does update method works. Here is the code: Code: [Select] public function update() { global $database; // Don't forget your SQL syntax and good habits: // - UPDATE table SET key='value', key='value' WHERE condition // - single-quotes around all values // - escape all values to prevent SQL injection $attributes = $this->sanitized_attributes(); $attribute_pairs = array(); foreach($attributes as $key => $value) { $attribute_pairs[] = "{$key}='{$value}'"; } $sql = "UPDATE ".self::$table_name." SET "; $sql .= join(", ", $attribute_pairs); $sql .= " WHERE id=". $database->escape_value($this->id); $database->query($sql); return ($database->affected_rows() == 1) ? true : false; } I have form like this to deal with update: Code: [Select] <form action="index.php?page=languages" enctype="multipart/form-data" method="POST"> <?php foreach($language as $lang){ ?> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" /> <label>Jezik</label><input type="text" size="50" name="language" value="<?php echo $lang->lang; ?>" /><br> <input type="hidden" name="id_lang" value="<?php echo $lang->id_lang; ?>" /> <label>Slika</label><input type="file" name="image"><?php echo "<img src=\"../images/"; echo $lang->image; echo "\">"; ?> <br> <label>Pozicija</label><input type="text" name="pozicija" value="<?php echo $lang->pozicija; ?>" size="2" /></p> <br> <input type="submit" name="submit_update" value="Unesi"> <?php } ?> </form> and code to start the function: Code: [Select] if(isset($_POST['submit_update'])) { $language = new Jezik(); $language->update(); } What next??? Hi I have a problem with the following: Code: [Select] <?php class ClassA { public $propertyClassName = "ClassB"; public function methodClassName() { return "ClassB"; } } class ClassB { public function bmethod() { echo "great!"; } } //works $a = new ClassA(); $b = new $a->propertyClassName(); $b->bmethod(); //doesn't work $a = new ClassA(); $b = new $a->methodClassName(); $b->bmethod(); ?> Of course I could do Code: [Select] <?php $a = new ClassA(); $className = $a->methodClassName(); $b = new $className; $b->bmethod(); ?>but isn't there a way to do this without saving the method's return to a variable? Thanks in advance flolam Using this locally works fine: $html = $name::add_content($name, $html); but i get the double colon error whe using it live. $name is a name of a valid class. What could throw this error when it works locally? Hi I have created a Database class that uses the singleton method. I have a query method within this class so i would call this to return an array of results. What i need to know is what would be the best way to use this returned array Database Class: Code: [Select] <?php class Database { private static $dbInstance; private $hostname; private $username; private $password; private $database; private function __construct() { $this->hostname = 'localhost'; $this->username = 'user'; $this->password = 'pass'; $this->database = 'test'; mysql_connect($this->hostname, $this->username, $this->password); mysql_select_db($this->database); } public static function getDBInstance() { if (!self::$dbInstance) { self::$dbInstance = new Database(); } return self::$dbInstance; } public function query($q) { return mysql_query($q); } } ?> Person Class: Code: [Select] <?php require_once('Database.php'); class person { public function getName($id) { $con = Database::getDBInstance(); $query = $con->query("select name from data where id = ".$id); $result = mysql_fetch_assoc($query); echo $result['name']; } } ?> Index page: Code: [Select] <?php require_once('person.php'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> <?php $person = new person(); $person->getName(1); echo "<br />"; $person->getName(2); ?> </body> </html> Well in the class UserValidator I have a public method validate(), which checks the validation type and then calls specific private methods to execute the validation script. It gets a bit tricky here since the method validate() has to decide what private method to call. I am thinking about using call_user_func_array(), the script currently looks like this below: Code: [Select] public function validate(){ // The core method validate, it sends requests to different private methods based on the type if(empty($this->type)) throw new Exception('The validation type is empty, something must be seriously wrong...'); if(is_array($this->type) and !is_array($this->value)) throw new Exception('Cannot have scalar value if the type is an array.'); if(!is_array($this->type) and is_array($this->value)) throw new Exception('Cannot have scalar type if the value is an array.'); // Now we are validating our user data or input! $validarray = array("register", "login", "password", "session", "email", "reset", "profile", "contacts", "friends"); foreach($this->type as $val){ $method = "{$val}validate"; if(in_array($val, $validarray)) call_user_func_array(array($this, $method), array()); } } The method to execute depends on the validation type passed into the validator class, so it is somewhat like a dynamic function call. The problem is, well, I am not sure if I am using call_user_func_array() properly. I read it from php manual that it needs to accept a class instance, but there is no such instance inside a class method so I use $this in the argument. Is this the correct way of using call_user_func_array()? If not, how am I supposed to do this? thanks. Hi people! class FirstOne{ public function FunctionOne($FirstInput){ //do stuff and output value return $value1; } } Then:- class SecondOne{ public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } } What I want to know is this, if I want to use FunctionOne() in Class SecondOne do I do it like this:- (Assume as I have instantiated the first class using $Test = new FirstOne(); ) class SecondOne{ function SecondedFunction(){ global $Test; return $Test->FunctionOne(); } public function FunctionTwo($AnotherInput){ //do stuff and output value return $value2; } public function FunctionThree(){ //some code here $this->Test->SecondedFunction();<--I think as I can omit the $this-> reference } } My point is: Do I have to do it this way or is there way of having this done through __construct() that would negate the need for a third party function? I have a version working, I just think that it is a little convoluted in the way as I have done it, so I thought I would ask you guys. Any help/advice is appreciated. Cheers Rw I have two classes: ## Admin.php <?php class Admin { public function __construct() { include("Config.php"); } /** * deletes a client * @returns true or false */ function deleteClient($id) { return mysql_query("DELETE FROM usernames WHERE id = '$id'"); } } ?> ## Projects.php <?php class Projects { public function __construct() { include("Config.php"); $this->admin = $admin; $this->dataFolder = $dataFolder; } /** * Deletes a project * @returns true or false */ function deleteProject($id) { $root = $_SERVER['DOCUMENT_ROOT']; $theDir = $root . $this->dataFolder; $sql = mysql_query("SELECT * FROM projectData WHERE proj_id = '$id'"); while ($row = mysql_fetch_array($sql)) { $mainFile = $row['path']; $thumb = $row['thumbnail']; if ($thumb != 'null') { unlink($theDir . "/" . substr($thumb,13)); } unlink($theDir . "/" . substr($mainFile,13)); } $delete = mysql_query("DELETE FROM projectData WHERE proj_id = '$id'"); $getDir = mysql_query("SELECT proj_path FROM projects WHERE id = '$id'"); $res = mysql_fetch_array($getDir); rmdir($theDir . "/" . $res['proj_path']); return mysql_query("DELETE FROM projects WHERE id = '$id'"); } } ?> How can I call deleteProject() from within Admin.php? I have these two classes: Code: [Select] <?php class A { private $id; public function __construct() { $this->id = '11111'; } public function getProperty($prop) { return $this->$prop; } }?> Code: [Select] <?php class B extends A { private $message = "Nope, can't see it"; public function __construct() { parent::__construct(); $this->message = "Yep, I can see it"; } }?> I tried this, but it just outputs the id (the first call) Code: [Select] $class = new B; echo $class->getProperty('id'); echo $class->getProperty('message'); Why is that? I thought I could use a parent method on a child property.. *EDIT* Using a public or protected visibility on the message property gets me the output I expect...how come? Can I not pass references into class properities from outside the object? class db_manipulation { private $connection = NULL; function __construct(&$database_connection) { $this->connection = $database_connection; if (!$this->connection) die('couldnt connection to database'); } function __destruct() { mysqli_close($this->connection); } } Results in: Warning: mysqli_close() [function.mysqli-close]: Couldn't fetch mysqli in I have an existing instance of my class Database, now I want to call that instance in my Session class, how would I go about doing this? Hi, I need to be able to call a class based on variables. E.G. I would normally do: Code: [Select] $action = new pattern1() but i would like to be able to do it dynamicaly: Code: [Select] $patNum = 1; $action = new pattern.$patNum.() Im wondering if that's possible? If so what would the correct syntax be? Many Thanks. I know I'm posting this inside the PHP coding board but I'm curious on how most handle this situation. I have a page that uses php to retrieve data from my database and I want to have it place a | in between each of the returned data which it does but it still places one after the last returned row. I'm wondering if I should do this with jquery load and then have it place that character in between each of the data or if there's a way to do it with php or what? Any ideas? Code: [Select] <?php require ("../header.php"); ?> <div id="titlehistory" class="content"> <h1 class="pageheading">Title History</h1> <?php $titlesQuery =" SELECT titles.titleName, titles.shortName FROM titles WHERE titles.statusID = 1 ORDER BY titles.ID"; $titlesResult = mysqli_query($dbc,$titlesQuery); ?> <p><span class="minilinks"> <?php while ( $row = mysqli_fetch_array ( $titlesResult, MYSQLI_ASSOC ) ) { $fieldarray=array('titleName','shortName'); foreach ($fieldarray as $fieldlabel) { ${$fieldlabel} = $row[$fieldlabel]; } echo '<a href="/titlehistory/'.$shortName.'">'.$titleName.'</a> |'; } ?> </span></p> <p class="nohistory">Please select a title to view.</p> </div> <?php require ("../footer.php"); ?> |