The Cache: Technology Expert's Forum
 
*
Welcome, Guest. Please login or register. September 16, 2019, 11:14:24 PM

Login with username, password and session length


Pages: [1] 2
  Print  
Author Topic: Nutballs learning PHP thread  (Read 6316 times)
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« on: September 12, 2007, 05:36:05 PM »

This is my learning PHP thread, so I dont start a bunch of threads.

First question or actually confirmation.

Includes are only included once they are encountered in the script correct?

So in otherwords, if I wrapped an include in an if statement that never is true, then the include will never actually get loaded right?

example:
if (1==2)
{
require_once("somefile.php");
}

that will never get included right? I know it will never get executed, but will it never actually get loaded?

The reason I ask is because in ASP includes are executed inline, but are actually loaded into memory as part of the preproccessing step.

So if you have two functions, named the same exact thing, in two different included files, the compiler would throw an error because of the duplicate function declaration. Even if one of the includes are in an If-Else clause allowing only 1 to be executed.

If the are not loaded until actually executed, this could be benificial to me.
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #1 on: September 12, 2007, 09:49:21 PM »

Includes are only included once they are encountered in the script correct?
True.

[clipped, re. ASP]
So if you have two functions, named the same exact thing, in two different included files, the compiler would throw an error because of the duplicate function declaration. Even if one of the includes are in an If-Else clause allowing only 1 to be executed.
PHP will not include another file until it is encountered in the standard program flow. If it is not encountered, it will not be included at all - not even the name space. So you could have a dozen different instances of the same function included based on a switch statement, for example.

However, I am curious about what you want to do here... because there may be other, more effective and efficient ways to do what you're looking for.
« Last Edit: September 12, 2007, 10:00:58 PM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #2 on: September 12, 2007, 10:12:29 PM »

mostly i just am looking to do conditional config file inclusion, instead of doing it at the actual level of the code. Same constant declarations, but different values in each file.
example would be to mode switch from a DEV instance to LIVE, depending on the domainname.
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #3 on: September 12, 2007, 10:25:14 PM »

Totally valid and handy.

include '/www/sites/aclient/' . ($mode=='dev') ? 'dev' : 'prod' . '/funcLib.php';

or

switch($mode)
{
   case 'dev':
      require_once('dev/funcList.php');
      break;
   case 'stage':
      require_once('stage/funcList.php');
      break;
   case 'production':
      require_once('prod/funcList.php');
      break;
}
$var = aFunctionFoundInAll3();

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
m0nkeymafia
Expert
****
Offline Offline

Posts: 240


Check it!


View Profile
« Reply #4 on: September 13, 2007, 12:57:20 AM »

Totally valid and handy.

include '/www/sites/aclient/' . ($mode=='dev') ? 'dev' : 'prod' . '/funcLib.php';

or

switch($mode)
{
   case 'dev':
      require_once('dev/funcList.php');
      break;
   case 'stage':
      require_once('stage/funcList.php');
      break;
   case 'production':
      require_once('prod/funcList.php');
      break;
}
$var = aFunctionFoundInAll3();

/p

that is cool
shame i dont actually go through development and release stages lol
Logged

I am Tyler Durden
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #5 on: September 13, 2007, 07:36:23 AM »

Looking this morning I forgot the most completely obvious one,

include "/www/sites/aclient/$mode/funcList.php";

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #6 on: September 14, 2007, 04:54:18 PM »

OK next question... Regarding Classes

using a snippet of perks database class from here:
http://www.perkiset.org/forum/php/perks_dbconnection_class-t129.0.html

can the class itself have parameters that are passed upon instantiating? so dbConnection(param1) for example?
is the double underscore in the var declarations anything special? or just a convention on perks part.
The "$doConnect=true" parameter in the dbconnect function. Is that a default for in case that parameter is not passed?
$this refers to the function or the class? im guessing class.
function &cloneConnection() errrr whats the & for?

is there no concept of public and private methods in php classes?
are there no properties in php classes? are the class level vars basically like properties in other languages?


Code:
class dbConnection
{
var $__connected;
var $__host;
var $__user;
var $__password;
var $__database;
var $__myConnection;
var $__lastQuery;
var $dataSet;
var $row;

function dbConnection($host, $user, $password, $database, $doConnect=true)
{
$this->__host = $host;
$this->__user = $user;
$this->__password = $password;
$this->__database = $database;
$this->__connected = false;
}
function &cloneConnection()
{
if (!$this->__connected) { $this->connect(); }
return new dbConnection($this->__host, $this->__user, $this->__password, $this->__database);
}
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #7 on: September 14, 2007, 07:18:08 PM »

So is there any issue with context switching over and over again in a page? ASP could generally care less.

example:
Code:
<?php function content() { //START CONTENT HTML============================================= ?>

<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
Email: <input type="text" name="email" /><br/>
Password: <input type="password" name="pass" /><br/>
<input type="checkbox" name="remember" value="yes" /> Remember Me<br/>
<input type="submit" value="Login" />
</form>

<?php //END CONTENT HTML================================================================== ?>

I know this just made perk shiver... But it works really well for my "keep code outta the designers hands" template framework.
In asp you do a large chunk of HTML and just drop in <%=somefunctionthatreturnstext%> wherever you need it.
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #8 on: September 14, 2007, 08:52:25 PM »

can the class itself have parameters that are passed upon instantiating? so dbConnection(param1) for example?
Yes. You can redefine the param list for any constructor in a hierarichy. If you do, you are responsible, of course, for correctly calling your parent.

is the double underscore in the var declarations anything special? or just a convention on perks part.
The "$doConnect=true" parameter in the dbconnect function. Is that a default for in case that parameter is not passed?
There are a bunch of magic functions... __construct __destruct, __get __set, __isset, __unset, __call, __autoload, __sleep, __wakeup and __clone. I'll leave it to you to figger out which does what... but in this case, the __ is PHP's convention. I have, however, taken to personally use this same convention for things that I want to remember as "magic."

$this refers to the function or the class? im guessing class.
Zactly - the self-instance reference

function &cloneConnection() errrr whats the & for?
return a reference rather than a value... in that case, I am returning a reference to an object that is created in that function.

is there no concept of public and private methods in php classes?
Not in PHP4, but in PHP5 there is private, protected and public. There are still a few providers out there that use 4.3.4 (the earliest version that is really still viable) but anyone worth there salt has been into 5 for a couple years.

are there no properties in php classes? are the class level vars basically like properties in other languages?
Properties in a PHP class are simply variable references. To have an exposed property you'd do this:

Code:
class myclass
{
private $var1;
protected $var2;
public $var3;
}

... in that instance, you can talk to $var 3 but not 1 or 2. IMPORTANT: I could easily do this:

Code:
$anObj->aVariableThatWasNeverDefined = true;

this is completely valid. The new variable will be attached to <that> instance of the class and you can use it in a read/write way. I think this sucks. This means that you can misspell a var while assigning it to an object and never know that THAT's the reason things don't work later.

The way to get around this is to use the __get and __set magic funcs - with these you can trap all of the getting and setting of vars against $this. Using this functionality, you can replicate normal class events and "do stuff" on the setting of a variable, or prevent the getting of one... or ... well, you know.

Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #9 on: September 15, 2007, 11:19:37 AM »

NBs - we've been talking a lot about strings lately, I forgot one handy little item that many people forget:

PHP strings can be read (NOT WRITTEN) in a c-style ie., you can simply ask for the index position of the string rather than substring-ing something out :

$buff = 'ABCdefg';
$heavy = substr($buff, 2, 1);
$light = $buff[2];

$light and $heavy will have the same value, 'C'. Note that strings are zero indexed. Of course if you want a bizarre combo of strings then substr is better... or if you want a long segment of a string then substring is better... but if you want just the first char for example this is *way* faster. This array notation can be used in string dereferences as well, so you could do something like this:

$buff = 'abcdefg';
echo "The second char in '$buff' is {$buff[1]} and the fourth one is {$buff[3]}.";

Note also how you must enclose complex variable names (arrays, object references) in a dereferencing string within curly braces.

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #10 on: September 15, 2007, 12:24:25 PM »

So a string is stored as an actual array? interesting.

Is substr faster than doing a for loop to get 3 characters from the string for example?

for ( $i= 2; $i== 4; $i+= 1)
{
  echo $buff[$i];
}
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #11 on: September 15, 2007, 12:50:40 PM »

So a string is stored as an actual array? interesting.
That's C for you - I love that about C[++/#/whatever] - strings are literally just arrays of bytes terminated by a chr(0) usually. PHP allows you to read them this way, but not write them. For an example of how to work with C strings and how efficient they are, relook at my IPToNum PHP extension function experiment.

Is substr faster than doing a for loop to get 3 characters from the string for example?

for ( $i= 2; $i== 4; $i+= 1)
{
  echo $buff[$i];
}
I'd make the cutoff at about 2 chars... because you're having to move between the PCode and C as the processor runns your script... and the latency added by more code to get the strings (the for loop in your example) would be larger than the overhead of a single call to get a portion of the string. In fact, I'd say that unless you want only 1 or 2 chars I'd use the substr. I thought of this just this morning as I was writing a little processor to handle a particular type of string:
0FirstWord
1Another Phrase
0Some Phrase
3Something Else

... the first char was the "type" of the element and the second half contained names of people. So I parsed it like this:
$type = $inBuff[0];
$name = substr($inBuff, 1, 1024);

... because substr will only go out as far as the string is big. I think this is about the most optimal way to use this trick, although I may be wrong. Sure has been known to happen Wink

IMPORTANT: All this talk about latency is really only a guiding point, because PHP is still fast as shit through a goose. I always think from efficiency first, rather than trying to refactor for speed later. Consider this function which will capitalize a name, regardless of dashes, apostrophes or Mc and Mac:

Code:
function cleanup($name)
{
$name = strtolower(trim($name));
$name = join('-', array_map('ucwords', explode('-', $name)));
$name = join('\'', array_map('ucwords', explode('\'', $name)));
$name = join('Mac', array_map('ucwords', explode('Mac', $name)));
$name = join('Mc', array_map('ucwords', explode('Mc', $name)));
return $name;
}

You'd think, if you had a thousand rows in a DB and you used this function against them all that the latency would just be intolerable... but it's not. Once the code is compiled it is really durn fast.

/p
Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
nutballs
Administrator
Lifer
*****
Offline Offline

Posts: 5627


Back in my day we had 9 planets


View Profile
« Reply #12 on: September 19, 2007, 04:01:49 PM »

is this correct for inserting a date into a Date column in mysql (not date/time or timestamp, just DATE)? This seems hokey to me since in ASP there is a DateAdd function, but I cant find similar for PHP.

$timeframe=100;
$nextdate=date('Y-m-d',mktime(0, 0, 0, date("m")  , date("d")+$timeframe, date("Y")));
Logged

I could eat a bowl of Alphabet Soup and shit a better argument than that.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #13 on: September 19, 2007, 04:19:21 PM »

The correct format for MySQL would be:

$dateStr = date('Y-m-d H:i:s', time());

time() is a seconds since (the Unix epoch, I believe, but WGAF) - so calculating <now> exactly 100 days ago would be:

$aDay = 60*60*24; // 60 secs * 60 mins * 24 hours
$dateStr = date('Y-m-d H:i:s', time() - ($aDay * 100));

For use in a string, you could do something clever like this:

Code:
class nutballsDate
{
function MySQL() { return date('Y-m-d H:i:s', time()); }
function Proper() { return date('l FjS, Y', time()); }
}

$nbd = new nutballsDate();
$sql = <<<SQL
select *
from mytable, yourtable, thattable, thistable
where
adatefield <= '{$nbd->MySQL()}' and
someotherfield=anothervalue
order by lastname
SQL;


just so you don't need to test to see, the output would be:
MySQL() -> 2007-09-19 16:20:01
Proper() -> Wednesday September 19th, 2007

/p
« Last Edit: September 19, 2007, 04:20:55 PM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
perkiset
Olde World Hacker
Administrator
Lifer
*****
Offline Offline

Posts: 10096



View Profile
« Reply #14 on: September 19, 2007, 04:26:08 PM »

Further tickle:

Code:
class nutballsDate
{
protected $myDate;

__construct($theDate='')
{
if (!$theDate) {$theDate = time(); }
$this->myDate = $theDate;
}

function MySQL() { return date('Y-m-d H:i:s', $this->myDate); }
function Proper() { return date('l FjS, Y', $this->myDate); }
}

// Note that *of course* you'd use constants and other things here,
// but to avoid "magic numbers" I'm doing it mathy for thie example...

$nbd = new nutballsDate(time() + (60 * 60 * 24 * 100)); // 100 days in the future
$sql = "insert into mytable(datefield) values({$nbd->MySQL()})";


/p
« Last Edit: September 19, 2007, 04:28:44 PM by perkiset » Logged

It is now believed, that after having lived in one compound with 3 wives and never leaving the house for 5 years, Bin Laden called the U.S. Navy Seals himself.
Pages: [1] 2
  Print  
 
Jump to:  

Perkiset's Place Home   Best of The Cache   phpMyIDE: MySQL Stored Procedures, Functions & Triggers
Politics @ Perkiset's   Pinkhat's Perspective   
cache
mart
coder
programmers
ajax
php
javascript
Powered by MySQL Powered by PHP Powered by SMF 1.1.2 | SMF © 2006-2007, Simple Machines LLC
Seo4Smf v0.2 © Webmaster's Talks


Valid XHTML 1.0! Valid CSS!