I have a problem. I writed OOP in php, but it does not work. It gives me blank result. I putted screenshots of my code and result of that code above. Please analyse these codes and help me, how I can solve it. By the way my php version is 5.3. I can upgrade or downgrade it if it is important. Thanks.
index.php
<?php include('class_library.php'); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OOP ilk dersim)</title>
</head>
<body>
<?php
$phpders = new adam();
$padisah = new adam();
//----------
$phpders -> set_ad('NurlanXp 1');
$padisah -> set_ad('NurlanXp 2');
//------------
echo "PhpDersden gelen: ".$phpders -> get_ad;
echo "<br>Padisahdan gelen: ".$padisah -> get_ad;
?>
</body>
</html>
class_library.php
<?php
class adam{
var $ad;
function set_ad($yeni_ad){
$this -> ad = $yeni_ad;
}
function get_ad(){
return $this -> ad;
}
}
?>
index.php, class_library.php and the result of the code. Screenshots.
All documents in the same folder.
You seems using $padisah -> get_ad but your adam class doesn't have any getter metod so you have to use like
$padisah -> get_ad();
You can find working example on https://eval.in/591811
In Turkish: get_ad kısmının sonunda parantez açıp, kapatırsan sorun çözülür. Adam class'ının içerisinde getter metodu yok. Yukarıda verdiğim linkte sonundaki parantezle sorunun çözüldüğünü görebilirsin.
this is Your class:
<?php
class adam {
private $ad;
public function get_ad() {
return $this->ad;
}
public function set_ad($ad) {
$this->ad = $ad;
return $this;
}
}
and inside of code:
$phpders = new adam();
$padishah = new adam();
$phpders->set_ad('NurlanXP 1');
$padishah->set_ad('NurlanXP 2');
and usage of get_ad:
echo 'phpdersden gelen: '.$phpders->get_ad().'<br/>';
echo 'padishahdan gelen: '.$padishah->get_ad().'<br/>';
(After solving the issue mentioned by "num8er" - calling method with () ...)
Try to give an absolute include path
<?php include('/complete/path/to/class_library.php'); ?>
or set an appropriate include path set_include_path() before. You can use $_SERVER['DOCUMENT_ROOT'] as a base to build a path.
Related
I've got two files, like these two:
<?php
session_start();
class test{
public function login($code){
$app = JFactory::getApplication('site');
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query->select(array('id'))
->from($db->quoteName('#__users'))
->where($db->quoteName('code') . " = " . $db->quote($code));
$db->setQuery($query);//execute query
$results = $db->loadObjectList();//get results
if ($results[0] != null) {
$this->createSession($results[0]);
header("refresh:2;url=second_file.php");
}
return json_encode($results);
}
public function createSession($LoginInfo){
$_SESSION['userId']=$LoginInfo->id;
}
}
?>
and another php file like this:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<?php
echo $_SESSION['userId'];
?>
</body>
</html>
In the second page seems like that there is no information inside the session and i'm unable to get "userId" parameter.
PS: the first class php file is called by another php file where there is something like this:
require_once('test.class.php');
$mainframe = new test
if ($_GET['code']!=null) echo $mainframe->login($_GET['code']);
Where am I doing wrong? thanks.
PPS: All those file are hosted inside altervista.org and there is Joomla CMS installed.
I am working in yii framework.I am getting stuck at a point where I have to call a function inside controller in yii framework from core php file. Actually I am going to create html
snapshot.
my folder structure is
seoPravin--
--protected
--modules
--kp
--Dnycontentcategoriescontroller.php
--DnycontentvisitstatController.php
--themes
--start.php (This is my customized file)
--index.php
1) Code of start.php file :--
<!DOCTYPE HTML>
<html>
<head>
<?php
if (!empty($_REQUEST['_escaped_fragment_']))
{
$yii=dirname(__FILE__).'/yii_1.8/framework/yii.php';
require_once($yii);
$escapeFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapeFragment);
include 'protected/components/Controller.php';
include 'protected/modules/'.$arr[0].'/controllers/'.$arr[1].'Controller.php';
echo DnycontentcategoriesController::actiongetDnyContent(); //gettting error at this point
?>
</head>
<body>
<?php
//echo "<br> ".$obj->actiongetDnyContent();
}
?>
</body>
</html>
2) yii side controller function : This function work for normal but when I am calling using escaped_fragment it gives error
public static function actiongetDnyContent()
{
if (!empty($_REQUEST['_escaped_fragment_']))//code inside if statement not working
{
$escapedFragment=$_REQUEST['_escaped_fragment_'];
$arr=explode('/',$escapedFragment);
$contentTitleId=end($arr);
$model = new Dnycontentvisitstat(); //Error got at this line
}
else //Below code is working properly
{
$dependency = new CDbCacheDependency('SELECT MAX(createDateTime) FROM dnycontent');
$content = new Dnycontent();
$content->contentTitleId = $_GET['contentTitleId'];
$content = $content->cache(2592000,$dependency)->getContent();
$userId=105;
$ipAddress=Yii::app()->request->userHostAddress;
echo "{\"contents\":[".CJSON::encode($content)."]} ";
$model = new Dnycontentvisitstat();
$model->save($_GET['contentTitleId'], $userId, $ipAddress);
}
}
error:
Fatal error: Class 'Dnycontentvisitstat' not found in
C:\wamp\www\seoPravin\protected\modules\KnowledgePortal\controllers\DnycontentcategoriesController.php
on line 289
code is working for normal url but not working for _esaped_fragment
It is a very bad practice but you can do a HTTP self request, like this:
include("http://{$_SERVER['HTTP_HOST']}/path/?r=controller/action&_param={$_GET['param']}");
Check http://www.php.net/manual/en/function.include.php to see how to enable HTTP includes.
I am a PHP beginner and trying to write PHP classes that work with HTML and MySql.
I am facing the following problem,
I have created a class called DatabaseManager that contains the function get_value. This function simply returns a value. In another file, I am calling this function on a button click using java script. But the link doesn't seem to work between the two files....Can someone help me?
thank you.
Here's my file that contains the PHP class.
<!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 content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
</head>
<body>
<?php
class DatabaseManager {
private $value=1;
public function get_value ()
{
return value;
}
}
/php>
</body>
</html>
and here's the other file that calls it.
<html>
<head>
<?php include("DatabaseManager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
The name of the file that contains the function get_value is DatabaseManager.php
DO Like this
In Databasemanager.php
<?php
class DatabaseManager {
private $value = 1;
public function get_value() {
return $this->value;
}
}
?>
In another PHP file
<html>
<head>
<?php include("Databasemanager.php"); ?>
<script type="text/javascript">
function connect()
{
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
}
</script>
</head>
<body>
<input type="button" value="Search " onclick="connect()">
</body>
</html>
A few things:
in DatabaseManager.php remove all HTML. You're including the file elsewhere, you don't need or want duplicated HTML tags.
Remove the # in your MySQL section. This suppresses any errors you are having.
Switch to PDO or MySQLi. They are safer (if used properly)
Your closing php tag is wrong in the database file. You have /php> it should be ?>
Your class does absolutely nothing as-is.
There are multiple things here that you're douing wrong.
You don't need the html code in the first example.
You close the php wrong /php> should generate an error, it should be ?>
When your instantiating your DatabaseManager class you've left out the parentheses which means that the constructor will never get called, this should also generate an error.
You're probably trying to use alert in javascript which in this case you're not doing.
It should look something like this instead:
<?php
class DatabaseManager {
private $value = 1;
function getValue() {
return $this->value;
}
}
?>
And in your html (still php, but the one containing the html-markup) file:
<html>
<head>
<script type="text/javascript">
function connect() {
alert("
<?php
include "nameofDBManagerClassFile.php"
$dbm = new DatabaseManager();
echo "the value is " . $dbm->getValue();
?>
");
}
</script>
</head>
<body>
</body>
</html>
It could also be that you think that the php-code that is inside of the javascript function will not be executed untill you call the JS function connect() this is not so. PHP code is executed on the server and thus will be called when a user requests that webpage, the javascript on the other hand is clientside and will be executed in the users browser. I highly recommend that you read up on both php and JavaScript.
You do it wrong way, to output something in your JavaScript function connect() make this :
function connect() {
alert("
<?php
$database_manager= new DatabaseManager;
echo "the value is" . $database_manager->get_value();
?>
");
}
because php code is executed apart from your on click event.
Actually it's unclear what you wish to get, but you misunderstand the basics.
[edited to clarify users question how to output something to the screen]
I think the easiest way is to use require i another file.
require('login.php');
function get_value()
{
return get_value;
}
Hey, I was following through a tutorial and was trying to simplify it to my needs. I cant get anything to work.. if unsure, some debugging tips would be great!
Here is the class.php file:
class MySQL{
public static function connect($set_host, $set_username, $set_password, $set_database){
mysql_connect("$set_host", "$set_username", "$set_password")or die("cannot connect");
mysql_select_db("$set_database")or die("cannot select DB");
}
}
class Posts {
public $id;
public $title;
function __construct($_id, $_title){
$this->id = $_id;
$this->title = $_title;
}
}
class Generate {
function queryPosts(){
$query = mysql_query("SELECT * FROM posts ORDER BY id DESC");
$postArray = array();
while ($row = mysql_fetch_assoc($query)){
$posts = new Posts($row["id"], $row['title']);
array_push($postArray, $posts);
}
return $postArray;
}
}
and here is the index:
<!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=utf-8" />
<title>dev</title>
</head>
<body>
<?php
include ("class.php");
MySQL::connect('localhost', 'test', 'pass', 'table');
$blog = Generate();
foreach ($blog as $post)
{
echo $post->title . "<br/>";
}
?>
</body>
</html>
I really cant get anything to generate with this method. The table/data is there, and I can display them in a procedural manner.. however I am trying to get into oop methods of doing this. Knowing me it's probably a really silly syntax error. Many thanks!
You're not using the new keyword, and then you're trying to iterate on $blog which is an object. You need to call the object's method, queryPosts, and iterate over it's results.
...
$blog = new Generate();
$posts = $blog->queryPosts();
foreach ($posts as $post) {
...
You should be instantiating Generate with new:
$blog = new Generate;
foreach($blog->queryPosts() as $postArray){
}
Another thing why are you putting " before and after the variable. It should be:
mysql_connect($set_host, $set_username, $set_password) or die("...");
As you may already know, #David's answer solves the problem quite well, however, since you said you were following a tutorial, I want to make you some recomendations so you don't go down into PHP's dark path.
You should consider putting different classes in different files
Having a Class to connect directly to the database is not that good, try to connect to the database on the queryPosts method and not in the index.php file
For starting purpouses, implementing data access like this will get you around the problem, but if you start working on more professionally oriented apps, consider using a ORM framework for data access, like Propel or Doctrine
Hope I can help!
The following codes are from http://d.hatena.ne.jp/dix3/20081002/1222899116 and codes are working well.
This is an example of using snoopy in codeigniter.
Q1. Am I correct to say that I can't use,
$this -> load -> library('snoopy')
since Snoopy.php does not create an object. And the example below is the way to do it?
If so, can you explain/direct me an tutorial or explanation of how to do it in details?
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Q2. Why do the author use
$to_specialchars=true
Is it needed for this?
Q3. Could you explain APPPATH and EXT.
APPPATH.'libraries/Snoopy'.EXT
I checked it in php.net but I could not find it. EXT must be extension, but can I use anywhere?
Thanks in advance.
I have a snoopy in application/library/Snoopy.php
I have application/library/Snoopy.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scraping{
var $c;
function Scraping(){
if ( ! class_exists('Snoopy'))
{
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
$this -> c = new Snoopy();
}
function getWebHtml($url="",$to_specialchars=true){
$this ->c -> fetch( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebText($url="",$to_specialchars=true){
$this -> c -> fetchtext( $url );
$str = mb_convert_encoding( (string) $this -> c -> results,"UTF-8","auto");
return ($to_specialchars) ? htmlspecialchars($str , ENT_QUOTES , "UTF-8" ) : $str ;
}
function getWebLinks($url=""){
$this -> c -> fetchlinks( $url );
return (array) $this-> c -> results ;
}
function getWebLinksText($url="",$delimiter="<br>"){
$arr = $this-> getWebLinks($url) ;
$ret ="";
foreach($arr as $k => $v){
$ret .= $v . $delimiter ;
}
return $ret;
}
} //endofclass
/* End of file Scraping.php */
/* Location: ./application/libraries/Scraping.php */
?>
I have a controller application/controller/mytasklist.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mytasklist extends Controller {
function Mytasklist()
{
parent :: Controller();
$this -> load -> helper( 'url' );
}
function index()
{
$data = "";
$this -> _SetTpl( $data );
}
function _SetTpl( $data )
{
$this -> load -> library("scraping");
$data["scraping"]["text"] = $this-> scraping -> getWebText("http://www.example.com/");
$data["scraping"]["html"] = $this-> scraping -> getWebHtml("http://www.example.com/");
$data["scraping"]["link"] = $this-> scraping -> getWebLinksText("http://www.example.com/","\n");
$tpl["page_title"] = "Welcome";
$tpl["main_content"] = $this -> load -> view( 'tasklist_view', $data , true );
$this -> load -> view( 'base_view', $tpl );
}
}
And I have a view, application/view/base_view.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<meta name="keywords" content="keyword here" />
<meta name="description" content="description here" />
<title><?php if(isset($page_title)){echo $page_title ;}?></title>
<?php if(isset($xajax_js)){echo $xajax_js ;}?>
<link href="http://127.0.0.1/ci_day4/css/mystyle.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="container">
<div id="rightblock">
<div id="content">
<?=$main_content?>
</div>
</div>
</div>
</body>
</html>
Q1. You can use:
$this->load->library('snoopy');
In your controllers. And create a new instance like so:
$snooper = new Snoopy();
The reason they are using:
if (!class_exists('Snoopy')) {
require_once(APPPATH.'libraries/Snoopy'.EXT);
}
Is because you will get a fatal error if you try and use $this->load->library(), since the loader class is not available in the library. You can call it in a controller is because your controllers extend the controller class, which extends the ci_base class, which extends the ci_loader class which is where the functionality to make calls like $this->load comes from. The Scraping class that you've shown here does not. If you dig down you'll see that the loader is basically using include_once to include whatever class, helper etc. you're trying to use.
Q2.
$to_specialchars = true
is being used in a couple the function declarations as parameters. Setting it '=true' is just setting a default, so you could can do this:
echo $scrappy->getWebHtml('http://example.com');
Which is identical to this:
echo $scrappy->getWebHtml('http://example.com', true);
If you look at the return statement of that function, you'll see they are $to_specialchars is being checked, and if it's true, then the output is run through the PHP function htmlspecialchars() first.
Q3. If you look at the root of your codeigniter project, in index.php you'll see EXT defined as:
define('EXT', '.'.pathinfo(__FILE__, PATHINFO_EXTENSION));
and APPATH:
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ($application_folder == '')
{
$application_folder = 'application';
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
So these are two constants being set at bootstrapping, so you can use them in your application, and if you were to ever change them, then it wouldn't instances like where you see it being used in the code you provided.
Please next time have one question per stackoverflow question :)
. This sample Scraping code was written based on using the library:
"Snoopy - the PHP net client ( snoopy.sourceforge.net )"
I tried to post it again. but I couldn't post with hyperlinks. sorry..
I'll answer to that in my site.(I'm a newbie stackoverflow.com :-( )
I think that I'll try to repost these answers after a few days .
( http://d.hatena.ne.jp/dix3/20091004 )