Get object class name from within parent class? - php

I am wanting to use the get_class($var) to show the class of an object. What would be the best way to do this? My code at the moment is:
abstract class userCharacter {
var $cName;
var $cLevel = 0;
var $cHP = 50;
var $cMP = 20;
function __construct($n) {
$this->cName = $n;
}
function showDetails() {
echo $this->cName . "<br />";
echo "Level: " . $this->cLevel . "<br />";
echo "HP: " . $this->cHP . "<br />";
echo "MP: " . $this->cMP . "<br />";
}
} // userCharacter
class warrior extends userCharacter {
} // warrior
And I create the object with:
$charOne = new warrior($name);
What I'm wanting to do is in the showDetails() function of the userCharacter class have a line similar to:
echo "Class: " . get_class($charOne) . "<br />";
But, I'm pretty sure that this won't work because the $charOne variable isn't in the right scope.
I'm thinking that I would need to declare $charOne with something like:
global $charOne = new warrior($name);
Would this work? If not, what is the best way to do this, if possible at all?

You want
echo get_class($this) ;
At runtime, the actual class will be figured out. That's what is cool about polymorphism.
However, even better, you want to do something like this:
echo $this->getClassDisplayName();
Then write that function for each subclass.
Or, the base class can have this type of function:
function getClassDisplayName()
{
return ($this->classDisplayName == "" ? getClass($this) : $this->classDisplayName );
}
Then in the constructor of your subclasses:
public __construct()
{
$this->classDisplayName = "The Mighty Warriors of Azgoth";
}

Related

PHP Call function from another function

Need to create function that will call other built-in and custom functions, problem is that each called function has different number of parameters.
I supply to a callerFunction required function name and required parameters in array, but how do i implement the actual function call?
P.S. I am aware of function scope, this is not a question now.
function myFunction(inputStr, paramOne, paramTwo) {
echo inputStr . " P1: " . paramOne . " P2: " . paramTwo;
}
function callerFunction(functName, functArgsArr) {
$myVar = "";
n = 1;
while n <= functArgsArr.length {
myVar = myVar . " " . functArgsArr[n];
n++;
}
%functName%("Hello World!", %myVar%);
}
callerFunction("myFunction", ["one", "two"]);
You could use the call_user_func_array PHP function:
<?php
function myFunction($inputStr, $paramOne, $paramTwo)
{
echo $inputStr . " P1: " . $paramOne . " P2: " . $paramTwo;
}
function callerFunction($functionName, array $functArgsArr)
{
// Prepends 'Hello World' to args array
array_unshift($functArgsArr, "Hello World");
// Calls $functionName passing the values of $functArgsArray as arguments
call_user_func_array($functionName, $functArgsArr);
}
callerFunction("myFunction", ["one", "two"]);
Working PHP Fiddle

PHP objects and arrays

Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble
if the price of a book is less than $20.00 output the book’s name and price
if the book’s title comes after the letter R in the alphabet output the book’s title.
My code so far is:
<?php
class Book {
// Properties
public $price;
public $title;
// Methods
function set_price($price) {
$this->price = $price;
}
function get_price() {
return $this->price;
}
function set_title($title) {
$this->title = $title;
}
function get_title() {
return $this->title;
}
}
$first_book = new Book();
$first_book->set_price('$13.95');
$first_book->set_title('Moby Dick');
echo "Price: " . $first_book->get_price();
echo "<br>";
echo "Title: " . $first_book->get_title();
echo "<br>";
$second_book = new Book();
$second_book->set_price('$23.99');
$second_book->set_title('Wuthering Heights');
echo "Price: " . $second_book->get_price();
echo "<br>";
echo "Title: " . $second_book->get_title();
echo "<br>";
$book = array("Moby Dick", "Wuthering Heights");
echo "Book Titles: " . $book[0] . ", " . " and " . $book[1] . ".";
?>
Kind Regurds
Kelly
Seems like you got most of it already, for the rest I would add a function to your Book class to get the first character of the title, and then use the ord (PHP documentation here) to convert it to an integer so you can check if it comes after the letter R.
<?php
// Add this to your Book class to get the first character of the title so we can check
// if the book comes after the letter 'R'
public function get_first_char() {
$titleArray = str_split($this->title);
return reset($titleArray);
}
// Instantiate your books and set properties ...
// Loop over each book
foreach ($book as $bookItem) {
$price = $bookItem->price;
// Right now $price is a string ('$xx.xx'), we need it to be numeric
$price = (float) substr($price, 1);
if ($price < 20) {
echo $bookItem->title;
echo $bookItem->price;
}
// Use the ord function to convert the ascii character into an int
if (ord(strtoupper($bookItem->get_first_char())) > ord('R')) {
echo $bookItem->title;
}
}
?>

How to call a function in PHP

I have been following some courses on how to create a session object, which has worked out fine, If I place the complete code onto a PHP file, all works great!
What I would like to do is place this in another module (PHP file) and just use one line (or equivalent) to do this, such as GetSessiondata();
<?php
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
?>
You need to "require" your file, where you want to use it.
Here an example
Working with classes:
Whatever.php
class Whatever {
public function __construct() {
// Ever when the code is instantiated, this will be called too!
}
public function myMethod() {
echo 'hello';
}
}
index.php
require_once('./Whatever.php');
$whatever = new Whatever();
$whatever->myMethod();
Without classes:
functions.php:
function whatever(){ echo 'hello'; }
index.php:
require_once('./functions.php');
whatever();
Read more:
Require: http://php.net/manual/es/function.require.php
Require_once: http://php.net/manual/es/function.require-once.php
My advise is to split this refactoring process into 2 steps:
1.Wrap your code into function:
function someFunctionName() {
$SqlCon = new DBConnect("Databaselocation","Database","Usr","Pss");
$UserDataSet = $SqlCon->GetUserList("SELECT * FROM Users");
echo "<br /><br />";
echo "<br /><br />";
if ($UserDataSet)
{
echo "<table>" . "<thead>" ;
echo "<tr><th scope=\"col\">" . 'Usr' . "</th>";
echo "<th scope=\"col\">" . 'Lvl' . "</th></tr></thead><tbody>";
foreach($UserDataSet as $data)
{
echo "<td>" .$data->GetUsrName()."</td>" ;
echo "<td>" .$data->GetUsrLevel()."</td></tr>" ;
}
echo "<tfoot><tr><th scope=\"row\" colspan=\"2\">" . 'Total Users = 2' . "</th></tr></tfoot>";
echo "</tbody>" . "</table>" ;
}
else
echo "Nothing Found in DB!";
}
// and call your function
someFunctionName();
2.Create another file, let's say functions.php, in the same dir and move function into it. Now you can require this file inside your php page:
require_once 'functions.php';
// and call your function
someFunctionName();
I think you are looking for include
Save your file, and then you can include it in another file as:
include 'my_file.php';
You can also use:
include_once
require
require_once
Read the documentation for further explanations or see this question

PHP file_get_html on Pinterest - Some seriously weird behaviour

Trying to scrape a bit of basic account info from Pinterest pages (no I'm not scraping pins before I get accused of using this maliciously, it's simply a competitor research tool).
Some accounts work fine with file_get_html, others return completely blank objects and I can't figure out why. I've built the below test code with completely random pages of different sizes to try and do some testing... still no further forward.
It uses Simple HTML DOM and here is my test code trying to figure out why some aren't working.
$pinterestUrl1 = "https://uk.pinterest.com/sfashionality/";
$pinterestUrl2 = "https://uk.pinterest.com/serenebathrooms/";
$pinterestUrl3 = "https://uk.pinterest.com/jenstanbrook/";
$pinterestUrl4 = "https://uk.pinterest.com/homebaseuk/";
$pinterestUrl5 = "https://uk.pinterest.com/thedoifter/";
$pinterestUrl6 = "https://uk.pinterest.com/coolshitibuy/";
$html1 = file_get_html($pinterestUrl1);
$html2 = file_get_html($pinterestUrl2);
$html3 = file_get_html($pinterestUrl3);
$html4 = file_get_html($pinterestUrl4);
$html5 = file_get_html($pinterestUrl5);
$html6 = file_get_html($pinterestUrl6);
echo $pinterestUrl1 . " - "; if (is_object($html1)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl2 . " - "; if (is_object($html2)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl3 . " - "; if (is_object($html3)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl4 . " - "; if (is_object($html4)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl5 . " - "; if (is_object($html5)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
echo $pinterestUrl6 . " - "; if (is_object($html6)) { echo "Returns object okay<br/>"; } else { echo "Failed<br/>"; };
Result:
https://uk.pinterest.com/sfashionality/ - Returns object okay
https://uk.pinterest.com/serenebathrooms/ - Returns object okay
https://uk.pinterest.com/jenstanbrook - Failed
https://uk.pinterest.com/homebaseuk/ - Failed
https://uk.pinterest.com/thedoifter/ - Returns object okay
https://uk.pinterest.com/coolshitibuy/ - Returns object okay
I can't see any reasons why some of these return objects and others don't... and because it's blank I don't even know where to start debugging this kind of thing.
Any ideas at all on this one? Thanks
Simple HTML DOM parser has constant MAX_FILE_SIZE with value 600000 and URLs that you are requesting have slightly more HTML.
You can define MAX_FILE_SIZE with some larger value before including lib, this will produce a PHP notice but HTML will be processed. Code I have tested this with:
<?php
define('MAX_FILE_SIZE', 6000000); //Will produce notice, but we need to define it
include_once './simplehtmldom_1_5/simple_html_dom.php';
$urls = array(
'https://uk.pinterest.com/sfashionality/',
'https://uk.pinterest.com/serenebathrooms/',
'https://uk.pinterest.com/jenstanbrook/',
'https://uk.pinterest.com/homebaseuk/',
'https://uk.pinterest.com/thedoifter/',
'https://uk.pinterest.com/coolshitibuy/',
);
foreach ($urls as $url) {
$content = file_get_contents($url);
$html = str_get_html($content);
echo $url . ' - ';
if (is_object($html)) {
echo 'Returns object okay<br/>';
} else {
echo 'Failed<br/>';
};
}

(EDITED QUES) PHP - Call function within another function

I have referred to similar questions like this and have done exactly the same way as it should have been but no success. Hence I would appreciate if some one can help me with this
I have a file called view.php which calls a function from a class based on a switch case condition. This function displays the output on the page with few links. When clicked on the link it calls another function which sits in my first function. But obviously when I click my link, nothing happens. That's my code.
view.php
require_once(..'/functions.php');
$functions = new myfile_functions();
<form method="post" action="view.php"><div>
<p><select name="potentialareas" id="potentialareas">
<option style="font-weight:bold;" value="-1">Select an area to view </option>
<?php
foreach($accessareas as $accessarea){
echo "<option value='".$accessarea->id."'>".$accessarea->name. " - " . $accessarea->reporttype. "</option>";
}
?>
</select>
</p>
<p><input name="view" id="view" type="submit" value="View" title="view" /><br /></p>
</div></form>
<div style="border-top:1px dotted #ccc;"></div>
<?php
if(isset($_POST['view']))
{
$hierarchyid = $_POST['potentialareas'];
$reporttype = $DB->get_record_sql("some query");
switch($reporttype->reporttype)
{
case "D Report":
$functions->getDepartmentReport($hierarchyid);
break;
case "S Report":
$functions->getSectionReport($hierarchyid);
break;
case "A Report":
$functions->getAreaReport($hierarchyid);
break;
}
}
functions.php
class myfile_functions(){
function getDepartmentReport($departmentid)
{
global $USER, $CFG, $DB;
$dname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $dname->name. " Department Report</b></p>";
$output .= "<p>Activities started: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofsections'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$snames = $DB->get_records_sql('some query');
foreach($snames as $sname)
{$output .= "<p>" .$sname->name. " <a href='view.php?section=" .$sname->id. "' name='section'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['section']))
{
$this->getSectionReport($_GET['section']);
}
echo $output;
}
function getSectionReport($sectionid)
{
global $USER, $CFG, $DB;
$sname = $DB->get_record_sql("some query");
$output = "<div id='actualreport'><p><b>" . $sname->name. " Report</b></p>";
$output .= "<p>Num Users: </p>";
$output .= "<p>Activities Completed: </p></div>";
$output .= "<div id='separator' style='border-top:1px dotted #ccc;'></div>";
$output .= "<div id='listofareas'><p><b><i>Select the following for a more detailed report.</i></b></p>";
$anames = $DB->get_records_sql('some query');
foreach($anames as $aname)
{$output .= "<p>" .$aname->name. " <a href='view.php?area=" .$aname->id. "' name='view' id='view'><i>view report</i></a></p>";
}
$output .= "</div>";
if(isset($_GET['area']))
{
$areaid = $_GET['area'];
$this->getAreaReport($areaid);
}
echo $output;
}
Similarly another function calling the above function, n so on.
function getAreaReport($id)
{ .. same content but calling another function...}
So when ever I click my view report link, I get the id appended id in my querystring, something like
http://mydomain.com/view.php?section=5
Ideally the contents of getSectionReport() should get printed but its not. Please point out what is it that I am doing wrong.
Thanks in advance.
What's your main method for displaying everything? At the moment you have three functions, all of which link to eachother in various ways, but it doesn't look as if you're instantiating anything first. The PHP is being fed a parameter in your URL, sure, but if a class isn't instantiated and a method declared, how does it know what you want it to do?
For myfile.php, maybe you should do something like:
class MyFile
{
public function other_function()
{
// Various stuff
return 'stuff';
}
public function other_other_function()
{
// Various other stuff
return 'other stuff';
}
public function page_view($file_id)
{
$var = $this->other_function($file_id);
return $this->other_other_function($var);
}
}
$class = new MyFile;
echo $class->page_view($_GET['id']);
If the two functions are part of a class (as your comment above hints), then the call should be written as
$this->getUserReport($id);
If you're accessing a sibling function inside the same class, use:
class ClassName
{
public function sibling_function()
{
return 'Hey bro!';
}
public function my_function()
{
return $this->sibling_function();
}
}
If not, use the standard:
public function my_function()
{
return sibling_function();
}
If you're still having trouble, make sure your class is properly instantiated. There's no point calling another function if you're not even instantiating the class first:
$obj = new ClassName;
echo $obj->my_function();

Categories