How to use a PHP object as an array - php

I have a heard time figuring out how to use a class as an array. This response helped me a bit on the way; but it doesn't work.
I have a class like this one:
class body_text
{
// class body_text's attributes
var $position;
var $content;
}
And I want to use it as an array:
$body_text_id = 0;
while ($row['page'] <> "")
{
$body_text[$body_text_id] -> position = trim($row["page"]);
$body_text[$body_text_id] -> content = trim($row["text");
$body_text_id++;
}
Now, it seems I would need to use this for my class
class body_text_class extends ArrayObject
and use this then:
$body_text = new body_text_class();
But that doesn't work.
I am sure there is a simple answer to this... but I can't find it. Thanks for any hints!
EDIT: Added another line in the loop to make it clearer. Sorry!
My aim: I get back many bits of text and its position within a website from a first query ("$row['page']"), and I want to store these in a variable for later use.

Hard to follow the code but you are just showing an array of objects:
for($i=0; $i<10; $i++) {
$body_text[$i] = new body_text;
$body_text[$i]->position = 'something';
}
print_r($body_text);

Related

Is it possible to get the list of the class alias in php as array?

example
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
How can I get the aliases (USE) as an array?
example of what I am looking to get
$test = [Test\One, Test\Two, Test\Tree];
Does anybody have any suggestions without scanning the file?
or is there a PHP function that will return the list aliases as an array?
Any help will be very appreciated.
Assuming I have the following class and the file is located and named as following file name and location src/Foo.php
namespace Foo;
use Test\One;
use Test\Two;
use Test\Three;
class Sample
{}
now I can scan this file
with this function, I can scan that class and get the result expected.
<?php
use \SplFileObject;
class Scanner
{
public static function getUseAliases()
{
$className = new SplFileObject("src/Foo.php");
$use = [];
while (!$className->eof())
{
$alias = explode("use ", $className->fgets());
if(!empty($alias[1]))
{
$use[] = trim($alias[1]);
}
}
$className = null; //Unset the file to prevent memory leaks
print_r($use);//will print my expected output [Test\One, Test\Two, Test\Three]
}
}
I think there should be a better way to get the same results and this is why I posted my current solution. Please let me know your thoughts.
You can try to use this class:
https://gist.github.com/Zeronights/7b7d90fcf8d4daf9db0c

how to include script of variables in a class? undefined variable

got a script which has string variables that represent data fields like they are in the database. because this project is a complete mess this is a stage in cleaning it up and not having to rewrite the field name in numerous locations.
so one script 'DataKeys.php' will have variables set to field names.
//results from query1
$keyField1 = 'field1';
$keyField2 = 'field2';
these two vars above is only a snippet of a much longer list.
I want to access this file and use these vars when I am formatting the data to be more friendly for the front end. this script is being accessed in a class however the fields, $keyField1, defined in the script is not being found in the class. I did have the actual string there but I think single access point would be best so when I make future changes I don't need search the whole project.
class DataFormatter {
//put your code here
public function __construct() {
$documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
include ($documentRoot . '/database/values/DataKeys.php');
}
public function cleanData($data){
if (is_null($data) || empty($data))
{
return;
}
foreach($data as $row){
$field1Value = $row[$keyField1];
unset($row[$keyField1]);
}
}
}
I also tried moving the include outside the class definition.
$documentRoot = filter_input(INPUT_SERVER, "DOCUMENT_ROOT");
include ($documentRoot . '/database/values/DataKeys.php');
The error that is being reported is :
Undefined variable: keyField1
SOULTION
Maybe not the optimal way but I took the include statement and placed it inside the function. The code above is just a demo of what I was trying to achieve not the actual code I am using.
the 2 variables are available just after the "include".
you can for example, put the 2 values in properties of the object
include ...;
$this->keyField1 = $keyField1;
$this->keyField2 = $keyField2;
You have to assign DataKeys.php to class member.
class DataFormatter {
private $keyField1;
private $keyField2;
public function __construct($filename) {
include $filename;
$this->keyField1 = $keyField1;
$this->keyField2 = $keyField2;
}
}
$dataFormatter = new DataFormatter(filter_input(INPUT_SERVER, 'DOCUMENT_ROOT') . '/database/values/DataKeys.php');

a function for creating shortname style variables in PHP

I'm just learning PHP, and I'm sure I'm not the first person to try something like this, but maybe because I didn't know what to call it, I couldn't find any other examples or questions on here or from a search on google.
I wanted to create a function which takes two parameters and uses them to create all the short style variables I'll be using later in my script.
My problem is where normally the syntax to create a short variable is something like:
$var = $_METHOD['var'];
but I'm trying to do this using variables and don't know how to get the syntax right. Here's my code:
<?php
session_start();
function shortnames($some_vars, $type) {
for ($i = 0; $i<(count($some_vars)); $i++) {
$$some_vars[$i] = $_$type['$some_vars[$i]'];
echo $$some_vars[$i].' = '.$some_vars[$i].'<br />';
}
}
$post_vars = array(lastname,firstname,payment);
$session_vars = array(sessiontxt,province,city,venue,regfee);
shortnames($session_vars,session);
shortnames($post_vars,post);
?>
Thanks for helping a beginner!!

Calling php method from external function produces error

function KeepSamePage($text)
{
$sb_w = $oPdf->GetStringWidth($text);
$num_lines = explode("\n",$text);
$total = 0;
foreach($num_lines as $line)
{
$y = $oPdf->GetY();
$page_height = 11 * 25.4;
$this_width = $oPdf->GetStringWidth(strip_tags($line));
$extra_line = floor($this_width / $w);
$is_line = $this_width / ($w - 1);
$is_line = $this_width == 0 ? 1 + $extra_line : ceil($is_line) + $extra_line;
$total = $total + $is_line;
}
$sb_height = $total * 5;
if(($page_height - $y) < $sb_height){ $oPdf->AddPage(); }
}
KeepSamePage($signature_block);
I'm using FPDF and I'm creating a function to keep the signature page of a letter all on the same page. This checks to see if it would go to the next page and if soo, then it does an AddPage();
The issue I'm having is that when I don't have it in a function, it works perfectly, but when I put it within a function, I get errors when calling the methods in the class represented by $oPdf.
So, my question generally is this: Is it possible to have a regular function in PHP call a class method as I have below? If it is possible, what am I doing wrong?
ERROR GENERATED IS:
Fatal error: Call to a member function GetStringWidth() on a non-object in /home/jarodmo/public_html/cms/attorney_signature_block.php on line 18
Oh, and an explanation of my function just in case you're interested or someone else finds it.
Text has \n for new lines in it so the PDF will put the text of the signature block on the next line. Each new array element should be a new line, so I would need to multiply the number of lines by my line height, 5 in this case. (See $total * 5).
I check to see where we are on the page, find the difference between the page height and the Y position, then check that against the height of the signature block. If the signature block is bigger, then it wouldn't fit and I know we need a manual page break.
Also, because I do the explode with the \n to see the lines, I also have to check to make sure that none of the lines is still wider than the page otherwise it would word wrap and really be 2 lines (or more) where I was only counting it as 1 because it was just one array element. I know a signature block shouldn't have text wide enough to be on 2 lines, but I wrote this to be applicable for more than just signature blocks. I wanted to be able to call this function anywhere I wanted to make sure certain text stayed on the same page. Call the function, check the text I'm about to write to the PDF and move on knowing that the desired text would all be on the same page.
Thanks for all of the help and comments. SO is the best.
$oPdf
is not defined on your code. You need to define it, and maybe read PHP variable scope.
You are trying to access methods of the $oPdf object in your function, but your function has no idea what $oPdf is, thus, the error message.
you have to do something like this.
function KeepSamePage($text) {
$oPdf = new your_string_class();
$sb_w = $oPdf->GetStringWidth($text);
}
or
$oPdf = new your_string_class();
function KeepSamePage($text, $oPdf) {
$sb_w = $oPdf->GetStringWidth($text);
}
Try the following:
function KeepSamePage($text) {
global $oPdf;
…
}
The problem is, that the object is defined outside your function and you will have to allow your function to access it.
// Edit:
If you want to avoid global for whatever reason, you will have to pass your object to the function like this:
function KeepSamePage($text, $oPdf) {
…
// IMPORTANT! $oPdf has changed in this function, so you will have to give it back
return $oPdf;
}
You can call your function like this:
$oPdf = KeepSamePage($signature_block, $oPdf);
The advantage is, that you see in the main thread, that your function might has changed the object.
// Edit 2: I think, I was wrong on the edit1 in your case. As you pass the complete object to the function every change does apply to the object, so the changes will still be existant without giving back the result. If this was a variable that was defined in the main thread, you would have to give back the new value:
$a = 1;
function result1($a) {
++$a;
}
function result2($a) {
return ++$a;
}
echo $a."\n"; // 1
result1($a);
echo $a."\n"; // 1
$a = result2($a);
echo $a."\n"; // 2

How to get the data in comments

as follow:
<?php
/*
* #I'm data
*/
function demo() {}
how to get "I'm data"?
thx
Well, if you are accessing it via the demo() function...
// #I'm Data
function demo(){
$script = file(__FILE__);
$comment = $script[__LINE__ - 5]; // 4 lines above, and 1 for arrays
$temp = explode("#", $comment);
return $temp[1];
}
If your code is inside a class, the correct way is to use reflection:
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
There's no obvious way to do it -- your script is blissfully unaware of its own comments.
However, you could probably hack it by having your script read itself as data, and then parse out whatever you're looking for:
<?php
$my_own_source = file_get_contents(__FILE__);
//some code to pull out exactly what you want here.

Categories